<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chapter 11 Data Types</title>
<link rel="stylesheet" href="mvl.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets + chunker.py v1.9.2" />
<link rel="start" href="index.html" title="{book-title}" />
<link rel="up" href="" title="" />
<link rel="prev" href="charset.html" title="Chapter 10 Character Sets, Collations, Unicode" />
<link rel="next" href="functions.html" title="Chapter 12 Functions and Operators" />
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 11 Data Types</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="charset.html">Prev</a> </td>
<th width="60%" align="center"></th>
<td width="20%" align="right"> <a accesskey="n" href="functions.html">Next</a></td>
</tr>
</table>
<hr>
</div>
<div class="chapter">
<div class="titlepage">
<div>
<div>
<h1 class="title"><a name="data-types"></a>Chapter 11 Data Types</h1>

</div>

</div>

</div>
<div class="toc">
<p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="data-types.html#numeric-types">11.1 Numeric Data Types</a></span></dt><dd><dl><dt><span class="section"><a href="data-types.html#numeric-type-syntax">11.1.1 Numeric Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#integer-types">11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT,
MEDIUMINT, BIGINT</a></span></dt><dt><span class="section"><a href="data-types.html#fixed-point-types">11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC</a></span></dt><dt><span class="section"><a href="data-types.html#floating-point-types">11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE</a></span></dt><dt><span class="section"><a href="data-types.html#bit-type">11.1.5 Bit-Value Type - BIT</a></span></dt><dt><span class="section"><a href="data-types.html#numeric-type-attributes">11.1.6 Numeric Type Attributes</a></span></dt><dt><span class="section"><a href="data-types.html#out-of-range-and-overflow">11.1.7 Out-of-Range and Overflow Handling</a></span></dt></dl></dd><dt><span class="section"><a href="data-types.html#date-and-time-types">11.2 Date and Time Data Types</a></span></dt><dd><dl><dt><span class="section"><a href="data-types.html#date-and-time-type-syntax">11.2.1 Date and Time Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#datetime">11.2.2 The DATE, DATETIME, and TIMESTAMP Types</a></span></dt><dt><span class="section"><a href="data-types.html#time">11.2.3 The TIME Type</a></span></dt><dt><span class="section"><a href="data-types.html#year">11.2.4 The YEAR Type</a></span></dt><dt><span class="section"><a href="data-types.html#timestamp-initialization">11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME</a></span></dt><dt><span class="section"><a href="data-types.html#fractional-seconds">11.2.6 Fractional Seconds in Time Values</a></span></dt><dt><span class="section"><a href="data-types.html#date-and-time-type-conversion">11.2.7 Conversion Between Date and Time Types</a></span></dt><dt><span class="section"><a href="data-types.html#two-digit-years">11.2.8 2-Digit Years in Dates</a></span></dt></dl></dd><dt><span class="section"><a href="data-types.html#string-types">11.3 String Data Types</a></span></dt><dd><dl><dt><span class="section"><a href="data-types.html#string-type-syntax">11.3.1 String Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#char">11.3.2 The CHAR and VARCHAR Types</a></span></dt><dt><span class="section"><a href="data-types.html#binary-varbinary">11.3.3 The BINARY and VARBINARY Types</a></span></dt><dt><span class="section"><a href="data-types.html#blob">11.3.4 The BLOB and TEXT Types</a></span></dt><dt><span class="section"><a href="data-types.html#enum">11.3.5 The ENUM Type</a></span></dt><dt><span class="section"><a href="data-types.html#set">11.3.6 The SET Type</a></span></dt></dl></dd><dt><span class="section"><a href="data-types.html#spatial-types">11.4 Spatial Data Types</a></span></dt><dd><dl><dt><span class="section"><a href="data-types.html#spatial-type-overview">11.4.1 Spatial Data Types</a></span></dt><dt><span class="section"><a href="data-types.html#opengis-geometry-model">11.4.2 The OpenGIS Geometry Model</a></span></dt><dt><span class="section"><a href="data-types.html#gis-data-formats">11.4.3 Supported Spatial Data Formats</a></span></dt><dt><span class="section"><a href="data-types.html#geometry-well-formedness-validity">11.4.4 Geometry Well-Formedness and Validity</a></span></dt><dt><span class="section"><a href="data-types.html#spatial-reference-systems">11.4.5 Spatial Reference System Support</a></span></dt><dt><span class="section"><a href="data-types.html#creating-spatial-columns">11.4.6 Creating Spatial Columns</a></span></dt><dt><span class="section"><a href="data-types.html#populating-spatial-columns">11.4.7 Populating Spatial Columns</a></span></dt><dt><span class="section"><a href="data-types.html#fetching-spatial-data">11.4.8 Fetching Spatial Data</a></span></dt><dt><span class="section"><a href="data-types.html#optimizing-spatial-analysis">11.4.9 Optimizing Spatial Analysis</a></span></dt><dt><span class="section"><a href="data-types.html#creating-spatial-indexes">11.4.10 Creating Spatial Indexes</a></span></dt><dt><span class="section"><a href="data-types.html#using-spatial-indexes">11.4.11 Using Spatial Indexes</a></span></dt></dl></dd><dt><span class="section"><a href="data-types.html#json">11.5 The JSON Data Type</a></span></dt><dt><span class="section"><a href="data-types.html#data-type-defaults">11.6 Data Type Default Values</a></span></dt><dt><span class="section"><a href="data-types.html#storage-requirements">11.7 Data Type Storage Requirements</a></span></dt><dt><span class="section"><a href="data-types.html#choosing-types">11.8 Choosing the Right Type for a Column</a></span></dt><dt><span class="section"><a href="data-types.html#other-vendor-data-types">11.9 Using Data Types from Other Database Engines</a></span></dt></dl>
</div>
<p>
    MySQL supports <a class="link" href="glossary.html#glos_sql" title="SQL">SQL</a> data types in
    several categories: numeric types, date and time types, string
    (character and byte) types, spatial types, and the
    <a class="link" href="data-types.html#json" title="11.5 The JSON Data Type"><code class="literal">JSON</code></a> data type. This chapter provides
    an overview and more detailed description of the properties of the
    types in each category, and a summary of the data type storage
    requirements. The initial overviews are intentionally brief. Consult
    the more detailed descriptions for additional information about
    particular data types, such as the permissible formats in which you
    can specify values.
  </p><a class="indexterm" name="idm46444338747520"></a><a class="indexterm" name="idm46444338746448"></a><a class="indexterm" name="idm46444338744960"></a><a class="indexterm" name="idm46444338743472"></a><p>
    Data type descriptions use these conventions:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
        For integer types, <em class="replaceable"><code>M</code></em> indicates the
        maximum display width. For floating-point and fixed-point types,
        <em class="replaceable"><code>M</code></em> is the total number of digits that
        can be stored (the precision). For string types,
        <em class="replaceable"><code>M</code></em> is the maximum length. The maximum
        permissible value of <em class="replaceable"><code>M</code></em> depends on the
        data type.
      </p><a class="indexterm" name="idm46444338738688"></a><a class="indexterm" name="idm46444338737616"></a><a class="indexterm" name="idm46444338736128"></a><a class="indexterm" name="idm46444338735056"></a><a class="indexterm" name="idm46444338733568"></a><a class="indexterm" name="idm46444338732496"></a></li><li class="listitem"><p>
        <a class="indexterm" name="idm46444338730368"></a>

        <a class="indexterm" name="idm46444338729296"></a>

        <a class="indexterm" name="idm46444338727808"></a>

        <a class="indexterm" name="idm46444338726736"></a>

        <em class="replaceable"><code>D</code></em> applies to floating-point and
        fixed-point types and indicates the number of digits following
        the decimal point (the scale). The maximum possible value is 30,
        but should be no greater than
        <em class="replaceable"><code>M</code></em>−2.
      </p></li><li class="listitem"><p>
        <em class="replaceable"><code>fsp</code></em> applies to the
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> types and represents
        fractional seconds precision; that is, the number of digits
        following the decimal point for fractional parts of seconds. The
        <em class="replaceable"><code>fsp</code></em> value, if given, must be in the
        range 0 to 6. A value of 0 signifies that there is no fractional
        part. If omitted, the default precision is 0. (This differs from
        the standard SQL default of 6, for compatibility with previous
        MySQL versions.)
      </p><a class="indexterm" name="idm46444338718704"></a><a class="indexterm" name="idm46444338717616"></a></li><li class="listitem"><p>
        Square brackets (<code class="literal">[</code> and <code class="literal">]</code>)
        indicate optional parts of type definitions.
</p><a class="indexterm" name="idm46444338713888"></a><a class="indexterm" name="idm46444338712400"></a></li></ul>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="numeric-types"></a>11.1 Numeric Data Types</h2>

</div>

</div>

</div>
<div class="toc">
<dl class="toc"><dt><span class="section"><a href="data-types.html#numeric-type-syntax">11.1.1 Numeric Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#integer-types">11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT,
MEDIUMINT, BIGINT</a></span></dt><dt><span class="section"><a href="data-types.html#fixed-point-types">11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC</a></span></dt><dt><span class="section"><a href="data-types.html#floating-point-types">11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE</a></span></dt><dt><span class="section"><a href="data-types.html#bit-type">11.1.5 Bit-Value Type - BIT</a></span></dt><dt><span class="section"><a href="data-types.html#numeric-type-attributes">11.1.6 Numeric Type Attributes</a></span></dt><dt><span class="section"><a href="data-types.html#out-of-range-and-overflow">11.1.7 Out-of-Range and Overflow Handling</a></span></dt></dl>
</div>
<a class="indexterm" name="idm46444338709920"></a><a class="indexterm" name="idm46444338708432"></a><a class="indexterm" name="idm46444338706944"></a><p>
      MySQL supports all standard SQL numeric data types. These types
      include the exact numeric data types
      (<a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INTEGER</code></a>,
      <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a>,
      <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a>, and
      <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">NUMERIC</code></a>), as well as the
      approximate numeric data types
      (<a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a>,
      <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">REAL</code></a>, and
      <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE PRECISION</code></a>). The keyword
      <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a> is a synonym for
      <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INTEGER</code></a>, and the keywords
      <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DEC</code></a> and
      <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">FIXED</code></a> are synonyms for
      <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a>. MySQL treats
      <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> as a synonym for
      <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE PRECISION</code></a> (a nonstandard
      extension). MySQL also treats <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">REAL</code></a>
      as a synonym for <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE PRECISION</code></a>
      (a nonstandard variation), unless the
      <a class="link" href="server-administration.html#sqlmode_real_as_float"><code class="literal">REAL_AS_FLOAT</code></a> SQL mode is
      enabled.
    </p><p>
      The <a class="link" href="data-types.html#bit-type" title="11.1.5 Bit-Value Type - BIT"><code class="literal">BIT</code></a> data type stores bit values
      and is supported for <a class="link" href="storage-engines.html#myisam-storage-engine" title="16.2 The MyISAM Storage Engine"><code class="literal">MyISAM</code></a>,
      <a class="link" href="storage-engines.html#memory-storage-engine" title="16.3 The MEMORY Storage Engine"><code class="literal">MEMORY</code></a>,
      <a class="link" href="innodb-storage-engine.html" title="Chapter 15 The InnoDB Storage Engine"><code class="literal">InnoDB</code></a>, and
      <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> tables.
    </p><p>
      For information about how MySQL handles assignment of out-of-range
      values to columns and overflow during expression evaluation, see
      <a class="xref" href="data-types.html#out-of-range-and-overflow" title="11.1.7 Out-of-Range and Overflow Handling">Section 11.1.7, “Out-of-Range and Overflow Handling”</a>.
    </p><p>
      For information about storage requirements of the numeric data
      types, see <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>.
    </p><p>
      For descriptions of functions that operate on numeric values, see
      <a class="xref" href="functions.html#numeric-functions" title="12.5 Numeric Functions and Operators">Section 12.5, “Numeric Functions and Operators”</a>. The data type used for the
      result of a calculation on numeric operands depends on the types
      of the operands and the operations performed on them. For more
      information, see <a class="xref" href="functions.html#arithmetic-functions" title="12.5.1 Arithmetic Operators">Section 12.5.1, “Arithmetic Operators”</a>.
</p>
<div class="section">

<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="numeric-type-syntax"></a>11.1.1 Numeric Data Type Syntax</h3>
</div>
</div>
</div>
<a class="indexterm" name="idm46444338671632"></a><a class="indexterm" name="idm46444338670592"></a><a class="indexterm" name="idm46444338669520"></a><p>
        For integer data types, <em class="replaceable"><code>M</code></em> indicates
        the maximum display width. The maximum display width is 255.
        Display width is unrelated to the range of values a type can
        store, as described in
        <a class="xref" href="data-types.html#numeric-type-attributes" title="11.1.6 Numeric Type Attributes">Section 11.1.6, “Numeric Type Attributes”</a>.
      </p><p>
        For floating-point and fixed-point data types,
        <em class="replaceable"><code>M</code></em> is the total number of digits that
        can be stored.
      </p><p>
        As of MySQL 8.0.17, the display width attribute is deprecated
        for integer data types and support for it will be removed in a
        future MySQL version.
      </p><p>
        If you specify <code class="literal">ZEROFILL</code> for a numeric column,
        MySQL automatically adds the <code class="literal">UNSIGNED</code>
        attribute to the column.
      </p><p>
        As of MySQL 8.0.17, the <code class="literal">ZEROFILL</code> attribute is
        deprecated for numeric data types and support for it will be
        removed in a future MySQL version. Consider using an alternative
        means of producing the effect of this attribute. For example,
        applications could use the <a class="link" href="functions.html#function_lpad"><code class="literal">LPAD()</code></a>
        function to zero-pad numbers up to the desired width, or they
        could store the formatted numbers in
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> columns.
      </p><p>
        Numeric data types that permit the <code class="literal">UNSIGNED</code>
        attribute also permit <code class="literal">SIGNED</code>. However, these
        data types are signed by default, so the
        <code class="literal">SIGNED</code> attribute has no effect.
      </p><p>
        As of MySQL 8.0.17, the <code class="literal">UNSIGNED</code> attribute is
        deprecated for columns of type
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a>,
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a>, and
        <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> (and any synonyms) and
        support for it will be removed in a future MySQL version.
        Consider using a simple <code class="literal">CHECK</code> constraint
        instead for such columns.
      </p><p>
        <code class="literal">SERIAL</code> is an alias for <code class="literal">BIGINT
        UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE</code>.
      </p><p>
        <code class="literal">SERIAL DEFAULT VALUE</code> in the definition of an
        integer column is an alias for <code class="literal">NOT NULL AUTO_INCREMENT
        UNIQUE</code>.
</p>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Warning
</div>
<p>
          When you use subtraction between integer values where one is
          of type <code class="literal">UNSIGNED</code>, the result is unsigned
          unless the
          <a class="link" href="server-administration.html#sqlmode_no_unsigned_subtraction"><code class="literal">NO_UNSIGNED_SUBTRACTION</code></a> SQL
          mode is enabled. See <a class="xref" href="functions.html#cast-functions" title="12.10 Cast Functions and Operators">Section 12.10, “Cast Functions and Operators”</a>.
</p>
</div>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <a class="indexterm" name="idm46444338641280"></a>

            <a class="indexterm" name="idm46444338640208"></a>

            <a class="link" href="data-types.html#bit-type" title="11.1.5 Bit-Value Type - BIT"><code class="literal">BIT[(<em class="replaceable"><code>M</code></em>)]</code></a>
          </p><p>
            A bit-value type. <em class="replaceable"><code>M</code></em> indicates the
            number of bits per value, from 1 to 64. The default is 1 if
            <em class="replaceable"><code>M</code></em> is omitted.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338632416"></a>

            <a class="indexterm" name="idm46444338631344"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A very small integer. The signed range is
            <code class="literal">-128</code> to <code class="literal">127</code>. The
            unsigned range is <code class="literal">0</code> to
            <code class="literal">255</code>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338621632"></a>

            <a class="indexterm" name="idm46444338620560"></a>

            <a class="indexterm" name="idm46444338619488"></a>

            <a class="indexterm" name="idm46444338618000"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BOOL</code></a>,
            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BOOLEAN</code></a>
          </p><p>
            These types are synonyms for
            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT(1)</code></a>. A value of zero
            is considered false. Nonzero values are considered true:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT IF(0, 'true', 'false');</code></strong>
+------------------------+
| IF(0, 'true', 'false') |
+------------------------+
| false                  |
+------------------------+

mysql&gt; <strong class="userinput"><code>SELECT IF(1, 'true', 'false');</code></strong>
+------------------------+
| IF(1, 'true', 'false') |
+------------------------+
| true                   |
+------------------------+

mysql&gt; <strong class="userinput"><code>SELECT IF(2, 'true', 'false');</code></strong>
+------------------------+
| IF(2, 'true', 'false') |
+------------------------+
| true                   |
+------------------------+
</pre><p>
            However, the values <code class="literal">TRUE</code> and
            <code class="literal">FALSE</code> are merely aliases for
            <code class="literal">1</code> and <code class="literal">0</code>, respectively,
            as shown here:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT IF(0 = FALSE, 'true', 'false');</code></strong>
+--------------------------------+
| IF(0 = FALSE, 'true', 'false') |
+--------------------------------+
| true                           |
+--------------------------------+

mysql&gt; <strong class="userinput"><code>SELECT IF(1 = TRUE, 'true', 'false');</code></strong>
+-------------------------------+
| IF(1 = TRUE, 'true', 'false') |
+-------------------------------+
| true                          |
+-------------------------------+

mysql&gt; <strong class="userinput"><code>SELECT IF(2 = TRUE, 'true', 'false');</code></strong>
+-------------------------------+
| IF(2 = TRUE, 'true', 'false') |
+-------------------------------+
| false                         |
+-------------------------------+

mysql&gt; <strong class="userinput"><code>SELECT IF(2 = FALSE, 'true', 'false');</code></strong>
+--------------------------------+
| IF(2 = FALSE, 'true', 'false') |
+--------------------------------+
| false                          |
+--------------------------------+
</pre><p>
            The last two statements display the results shown because
            <code class="literal">2</code> is equal to neither
            <code class="literal">1</code> nor <code class="literal">0</code>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338594272"></a>

            <a class="indexterm" name="idm46444338593200"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A small integer. The signed range is
            <code class="literal">-32768</code> to <code class="literal">32767</code>. The
            unsigned range is <code class="literal">0</code> to
            <code class="literal">65535</code>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338583424"></a>

            <a class="indexterm" name="idm46444338582352"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MEDIUMINT[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A medium-sized integer. The signed range is
            <code class="literal">-8388608</code> to <code class="literal">8388607</code>.
            The unsigned range is <code class="literal">0</code> to
            <code class="literal">16777215</code>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338572592"></a>

            <a class="indexterm" name="idm46444338571520"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A normal-size integer. The signed range is
            <code class="literal">-2147483648</code> to
            <code class="literal">2147483647</code>. The unsigned range is
            <code class="literal">0</code> to <code class="literal">4294967295</code>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338562480"></a>

            <a class="indexterm" name="idm46444338561408"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INTEGER[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            This type is a synonym for
            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338553296"></a>

            <a class="indexterm" name="idm46444338552224"></a>

            <a class="indexterm" name="idm46444338550736"></a>

            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT[(<em class="replaceable"><code>M</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A large integer. The signed range is
            <code class="literal">-9223372036854775808</code> to
            <code class="literal">9223372036854775807</code>. The unsigned range
            is <code class="literal">0</code> to
            <code class="literal">18446744073709551615</code>.
          </p><p>
            <code class="literal">SERIAL</code> is an alias for <code class="literal">BIGINT
            UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE</code>.
          </p><p>
            Some things you should be aware of with respect to
            <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> columns:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                <a class="indexterm" name="idm46444338539696"></a>

                All arithmetic is done using signed
                <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> or
                <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> values, so you
                should not use unsigned big integers larger than
                <code class="literal">9223372036854775807</code> (63 bits) except
                with bit functions! If you do that, some of the last
                digits in the result may be wrong because of rounding
                errors when converting a
                <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> value to a
                <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a>.
              </p><p>
                MySQL can handle <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a>
                in the following cases:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: square; "><li class="listitem"><p>
                    When using integers to store large unsigned values
                    in a <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> column.
                  </p></li><li class="listitem"><p>
                    In
                    <a class="link" href="functions.html#function_min"><code class="literal">MIN(<em class="replaceable"><code>col_name</code></em>)</code></a>
                    or
                    <a class="link" href="functions.html#function_max"><code class="literal">MAX(<em class="replaceable"><code>col_name</code></em>)</code></a>,
                    where <em class="replaceable"><code>col_name</code></em> refers to
                    a <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> column.
                  </p></li><li class="listitem"><p>
                    When using operators
                    (<a class="link" href="functions.html#operator_plus"><code class="literal">+</code></a>,
                    <a class="link" href="functions.html#operator_minus"><code class="literal">-</code></a>,
                    <a class="link" href="functions.html#operator_times"><code class="literal">*</code></a>,
                    and so on) where both operands are integers.
</p></li></ul>
</div>
</li><li class="listitem"><p>
                You can always store an exact integer value in a
                <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> column by storing
                it using a string. In this case, MySQL performs a
                string-to-number conversion that involves no
                intermediate double-precision representation.
              </p></li><li class="listitem"><p>
                The <a class="link" href="functions.html#operator_minus"><code class="literal">-</code></a>,
                <a class="link" href="functions.html#operator_plus"><code class="literal">+</code></a>, and
                <a class="link" href="functions.html#operator_times"><code class="literal">*</code></a>
                operators use <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a>
                arithmetic when both operands are integer values. This
                means that if you multiply two big integers (or results
                from functions that return integers), you may get
                unexpected results when the result is larger than
                <code class="literal">9223372036854775807</code>.
</p></li></ul>
</div>
</li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338505792"></a>

            <a class="indexterm" name="idm46444338504720"></a>

            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL[(<em class="replaceable"><code>M</code></em>[,<em class="replaceable"><code>D</code></em>])]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A packed <span class="quote">“<span class="quote">exact</span>”</span> fixed-point number.
            <em class="replaceable"><code>M</code></em> is the total number of digits
            (the precision) and <em class="replaceable"><code>D</code></em> is the
            number of digits after the decimal point (the scale). The
            decimal point and (for negative numbers) the
            <code class="literal">-</code> sign are not counted in
            <em class="replaceable"><code>M</code></em>. If
            <em class="replaceable"><code>D</code></em> is 0, values have no decimal
            point or fractional part. The maximum number of digits
            (<em class="replaceable"><code>M</code></em>) for
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> is 65. The maximum
            number of supported decimals (<em class="replaceable"><code>D</code></em>)
            is 30. If <em class="replaceable"><code>D</code></em> is omitted, the
            default is 0. If <em class="replaceable"><code>M</code></em> is omitted,
            the default is 10.
          </p><p>
            <code class="literal">UNSIGNED</code>, if specified, disallows
            negative values. As of MySQL 8.0.17, the
            <code class="literal">UNSIGNED</code> attribute is deprecated for
            columns of type <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> (and
            any synonyms) and support for it will be removed in a future
            MySQL version. Consider using a simple
            <code class="literal">CHECK</code> constraint instead for such
            columns.
          </p><p>
            All basic calculations (<code class="literal">+, -, *, /</code>) with
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> columns are done with
            a precision of 65 digits.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338484864"></a>

            <a class="indexterm" name="idm46444338483792"></a>

            <a class="indexterm" name="idm46444338482720"></a>

            <a class="indexterm" name="idm46444338481648"></a>

            <a class="indexterm" name="idm46444338480192"></a>

            <a class="indexterm" name="idm46444338478704"></a>

            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DEC[(<em class="replaceable"><code>M</code></em>[,<em class="replaceable"><code>D</code></em>])]
            [UNSIGNED] [ZEROFILL]</code></a>,
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">NUMERIC[(<em class="replaceable"><code>M</code></em>[,<em class="replaceable"><code>D</code></em>])]
            [UNSIGNED] [ZEROFILL]</code></a>,
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">FIXED[(<em class="replaceable"><code>M</code></em>[,<em class="replaceable"><code>D</code></em>])]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            These types are synonyms for
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a>. The
            <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">FIXED</code></a> synonym is available
            for compatibility with other database systems.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338464768"></a>

            <a class="indexterm" name="idm46444338463696"></a>

            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT[(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A small (single-precision) floating-point number.
            Permissible values are <code class="literal">-3.402823466E+38</code>
            to <code class="literal">-1.175494351E-38</code>,
            <code class="literal">0</code>, and <code class="literal">1.175494351E-38</code>
            to <code class="literal">3.402823466E+38</code>. These are the
            theoretical limits, based on the IEEE standard. The actual
            range might be slightly smaller depending on your hardware
            or operating system.
          </p><p>
            <em class="replaceable"><code>M</code></em> is the total number of digits
            and <em class="replaceable"><code>D</code></em> is the number of digits
            following the decimal point. If <em class="replaceable"><code>M</code></em>
            and <em class="replaceable"><code>D</code></em> are omitted, values are
            stored to the limits permitted by the hardware. A
            single-precision floating-point number is accurate to
            approximately 7 decimal places.
          </p><p>
            <code class="literal">FLOAT(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
            is a nonstandard MySQL extension. As of MySQL 8.0.17, this
            syntax is deprecated and support for it will be removed in a
            future MySQL version.
          </p><p>
            <code class="literal">UNSIGNED</code>, if specified, disallows
            negative values. As of MySQL 8.0.17, the
            <code class="literal">UNSIGNED</code> attribute is deprecated for
            columns of type <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> (and
            any synonyms) and support for it will be removed in a future
            MySQL version. Consider using a simple
            <code class="literal">CHECK</code> constraint instead for such
            columns.
          </p><p>
            Using <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> might give you
            some unexpected problems because all calculations in MySQL
            are done with double precision. See
            <a class="xref" href="error-handling.html#no-matching-rows" title="B.4.4.7 Solving Problems with No Matching Rows">Section B.4.4.7, “Solving Problems with No Matching Rows”</a>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338443632"></a>

            <a class="indexterm" name="idm46444338442560"></a>

            <a class="indexterm" name="idm46444338441488"></a>

            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT(<em class="replaceable"><code>p</code></em>)
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A floating-point number. <em class="replaceable"><code>p</code></em>
            represents the precision in bits, but MySQL uses this value
            only to determine whether to use
            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> or
            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> for the resulting data
            type. If <em class="replaceable"><code>p</code></em> is from 0 to 24, the
            data type becomes <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> with
            no <em class="replaceable"><code>M</code></em> or
            <em class="replaceable"><code>D</code></em> values. If
            <em class="replaceable"><code>p</code></em> is from 25 to 53, the data type
            becomes <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> with no
            <em class="replaceable"><code>M</code></em> or <em class="replaceable"><code>D</code></em>
            values. The range of the resulting column is the same as for
            the single-precision <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> or
            double-precision <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> data
            types described earlier in this section.
          </p><p>
            <code class="literal">UNSIGNED</code>, if specified, disallows
            negative values. As of MySQL 8.0.17, the
            <code class="literal">UNSIGNED</code> attribute is deprecated for
            columns of type <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> (and
            any synonyms) and support for it will be removed in a future
            MySQL version. Consider using a simple
            <code class="literal">CHECK</code> constraint instead for such
            columns.
          </p><p>
            <a class="indexterm" name="idm46444338422736"></a>

            <a class="indexterm" name="idm46444338421664"></a>

            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT(<em class="replaceable"><code>p</code></em>)</code></a>
            syntax is provided for ODBC compatibility.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338415680"></a>

            <a class="indexterm" name="idm46444338414608"></a>

            <a class="indexterm" name="idm46444338413536"></a>

            <a class="indexterm" name="idm46444338412048"></a>

            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE[(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            A normal-size (double-precision) floating-point number.
            Permissible values are
            <code class="literal">-1.7976931348623157E+308</code> to
            <code class="literal">-2.2250738585072014E-308</code>,
            <code class="literal">0</code>, and
            <code class="literal">2.2250738585072014E-308</code> to
            <code class="literal">1.7976931348623157E+308</code>. These are the
            theoretical limits, based on the IEEE standard. The actual
            range might be slightly smaller depending on your hardware
            or operating system.
          </p><p>
            <em class="replaceable"><code>M</code></em> is the total number of digits
            and <em class="replaceable"><code>D</code></em> is the number of digits
            following the decimal point. If <em class="replaceable"><code>M</code></em>
            and <em class="replaceable"><code>D</code></em> are omitted, values are
            stored to the limits permitted by the hardware. A
            double-precision floating-point number is accurate to
            approximately 15 decimal places.
          </p><p>
            <code class="literal">DOUBLE(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
            is a nonstandard MySQL extension. As of MySQL 8.0.17, this
            syntax is deprecated and support for it will be removed in a
            future MySQL version.
          </p><p>
            <code class="literal">UNSIGNED</code>, if specified, disallows
            negative values. As of MySQL 8.0.17, the
            <code class="literal">UNSIGNED</code> attribute is deprecated for
            columns of type <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> (and
            any synonyms) and support for it will be removed in a future
            MySQL version. Consider using a simple
            <code class="literal">CHECK</code> constraint instead for such
            columns.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444338393168"></a>

            <a class="indexterm" name="idm46444338392080"></a>

            <a class="indexterm" name="idm46444338391008"></a>

            <a class="indexterm" name="idm46444338389520"></a>

            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE
            PRECISION[(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>,
            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">REAL[(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)]
            [UNSIGNED] [ZEROFILL]</code></a>
          </p><p>
            These types are synonyms for
            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a>. Exception: If the
            <a class="link" href="server-administration.html#sqlmode_real_as_float"><code class="literal">REAL_AS_FLOAT</code></a> SQL mode is
            enabled, <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">REAL</code></a> is a synonym
            for <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> rather than
            <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a>.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="integer-types"></a>11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT,
MEDIUMINT, BIGINT</h3>
</div>
</div>
</div>
<p>
        MySQL supports the SQL standard integer types
        <code class="literal">INTEGER</code> (or <code class="literal">INT</code>) and
        <code class="literal">SMALLINT</code>. As an extension to the standard,
        MySQL also supports the integer types
        <code class="literal">TINYINT</code>, <code class="literal">MEDIUMINT</code>, and
        <code class="literal">BIGINT</code>. The following table shows the
        required storage and range for each integer type.
</p>
<div class="table">
<a name="integer-type-storage-and-range"></a><p class="title"><b>Table 11.1 Required Storage and Range for Integer Types Supported by MySQL</b></p>
<div class="table-contents">
<table summary="Required storage and range for integer types supported by MySQL. Information includes the integer type, the storage size in bytes, the minimum signed and unsigned values, and the maximum signed and unsigned values."><col width="16%"><col width="16%"><col width="16%"><col width="16%"><col width="16%"><col width="16%"><thead><tr>
            <th scope="col">Type</th>
            <th scope="col">Storage (Bytes)</th>
            <th scope="col">Minimum Value Signed</th>
            <th scope="col">Minimum Value Unsigned</th>
            <th scope="col">Maximum Value Signed</th>
            <th scope="col">Maximum Value Unsigned</th>
          </tr></thead><tbody><tr>
            <td scope="row"><code class="literal">TINYINT</code></td>
            <td>1</td>
            <td><code class="literal">-128</code></td>
            <td><code class="literal">0</code></td>
            <td><code class="literal">127</code></td>
            <td><code class="literal">255</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">SMALLINT</code></td>
            <td>2</td>
            <td><code class="literal">-32768</code></td>
            <td><code class="literal">0</code></td>
            <td><code class="literal">32767</code></td>
            <td><code class="literal">65535</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">MEDIUMINT</code></td>
            <td>3</td>
            <td><code class="literal">-8388608</code></td>
            <td><code class="literal">0</code></td>
            <td><code class="literal">8388607</code></td>
            <td><code class="literal">16777215</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">INT</code></td>
            <td>4</td>
            <td><code class="literal">-2147483648</code></td>
            <td><code class="literal">0</code></td>
            <td><code class="literal">2147483647</code></td>
            <td><code class="literal">4294967295</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">BIGINT</code></td>
            <td>8</td>
            <td><code class="literal">-2<sup>63</sup></code></td>
            <td><code class="literal">0</code></td>
            <td><code class="literal">2<sup>63</sup>-1</code></td>
            <td><code class="literal">2<sup>64</sup>-1</code></td>
</tr></tbody></table>
</div>

</div>
<br class="table-break">
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="fixed-point-types"></a>11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC</h3>

</div>

</div>

</div>
<p>
        The <code class="literal">DECIMAL</code> and <code class="literal">NUMERIC</code>
        types store exact numeric data values. These types are used when
        it is important to preserve exact precision, for example with
        monetary data. In MySQL, <code class="literal">NUMERIC</code> is
        implemented as <code class="literal">DECIMAL</code>, so the following
        remarks about <code class="literal">DECIMAL</code> apply equally to
        <code class="literal">NUMERIC</code>.
      </p><p>
        MySQL stores <code class="literal">DECIMAL</code> values in binary format.
        See <a class="xref" href="functions.html#precision-math" title="12.25 Precision Math">Section 12.25, “Precision Math”</a>.
      </p><p>
        In a <code class="literal">DECIMAL</code> column declaration, the
        precision and scale can be (and usually is) specified. For
        example:
      </p><pre data-lang="sql" class="programlisting">salary DECIMAL(5,2)</pre><p>
        In this example, <code class="literal">5</code> is the precision and
        <code class="literal">2</code> is the scale. The precision represents the
        number of significant digits that are stored for values, and the
        scale represents the number of digits that can be stored
        following the decimal point.
      </p><p>
        Standard SQL requires that <code class="literal">DECIMAL(5,2)</code> be
        able to store any value with five digits and two decimals, so
        values that can be stored in the <code class="literal">salary</code>
        column range from <code class="literal">-999.99</code> to
        <code class="literal">999.99</code>.
      </p><p>
        In standard SQL, the syntax
        <code class="literal">DECIMAL(<em class="replaceable"><code>M</code></em>)</code> is
        equivalent to
        <code class="literal">DECIMAL(<em class="replaceable"><code>M</code></em>,0)</code>.
        Similarly, the syntax <code class="literal">DECIMAL</code> is equivalent
        to <code class="literal">DECIMAL(<em class="replaceable"><code>M</code></em>,0)</code>,
        where the implementation is permitted to decide the value of
        <em class="replaceable"><code>M</code></em>. MySQL supports both of these
        variant forms of <code class="literal">DECIMAL</code> syntax. The default
        value of <em class="replaceable"><code>M</code></em> is 10.
      </p><p>
        If the scale is 0, <code class="literal">DECIMAL</code> values contain no
        decimal point or fractional part.
      </p><p>
        The maximum number of digits for <code class="literal">DECIMAL</code> is
        65, but the actual range for a given <code class="literal">DECIMAL</code>
        column can be constrained by the precision or scale for a given
        column. When such a column is assigned a value with more digits
        following the decimal point than are permitted by the specified
        scale, the value is converted to that scale. (The precise
        behavior is operating system-specific, but generally the effect
        is truncation to the permissible number of digits.)
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="floating-point-types"></a>11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE</h3>

</div>

</div>

</div>
<p>
        The <code class="literal">FLOAT</code> and <code class="literal">DOUBLE</code> types
        represent approximate numeric data values. MySQL uses four bytes
        for single-precision values and eight bytes for double-precision
        values.
      </p><p>
        For <code class="literal">FLOAT</code>, the SQL standard permits an
        optional specification of the precision (but not the range of
        the exponent) in bits following the keyword
        <code class="literal">FLOAT</code> in parentheses; ; that is,
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT(<em class="replaceable"><code>p</code></em>)</code></a>.
        MySQL also supports this optional precision specification, but
        the precision value in
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT(<em class="replaceable"><code>p</code></em>)</code></a>
        is used only to determine storage size. A precision from 0 to 23
        results in a 4-byte single-precision <code class="literal">FLOAT</code>
        column. A precision from 24 to 53 results in an 8-byte
        double-precision <code class="literal">DOUBLE</code> column.
      </p><p>
        MySQL permits a nonstandard syntax:
        <code class="literal">FLOAT(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
        or
        <code class="literal">REAL(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
        or <code class="literal">DOUBLE
        PRECISION(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>.
        Here,
        <code class="literal">(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
        means than values can be stored with up to
        <em class="replaceable"><code>M</code></em> digits in total, of which
        <em class="replaceable"><code>D</code></em> digits may be after the decimal
        point. For example, a column defined as
        <code class="literal">FLOAT(7,4)</code> will look like
        <code class="literal">-999.9999</code> when displayed. MySQL performs
        rounding when storing values, so if you insert
        <code class="literal">999.00009</code> into a
        <code class="literal">FLOAT(7,4)</code> column, the approximate result is
        <code class="literal">999.0001</code>.
      </p><p>
        As of MySQL 8.0.17, the nonstandard
        <code class="literal">FLOAT(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
        and
        <code class="literal">DOUBLE(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>
        syntax is deprecated and support for it will be removed in a
        future MySQL version.
      </p><p>
        Because floating-point values are approximate and not stored as
        exact values, attempts to treat them as exact in comparisons may
        lead to problems. They are also subject to platform or
        implementation dependencies. For more information, see
        <a class="xref" href="error-handling.html#problems-with-float" title="B.4.4.8 Problems with Floating-Point Values">Section B.4.4.8, “Problems with Floating-Point Values”</a>
      </p><p>
        For maximum portability, code requiring storage of approximate
        numeric data values should use <code class="literal">FLOAT</code> or
        <code class="literal">DOUBLE PRECISION</code> with no specification of
        precision or number of digits.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="bit-type"></a>11.1.5 Bit-Value Type - BIT</h3>

</div>

</div>

</div>
<p>
        The <code class="literal">BIT</code> data type is used to store bit
        values. A type of
        <code class="literal">BIT(<em class="replaceable"><code>M</code></em>)</code> enables
        storage of <em class="replaceable"><code>M</code></em>-bit values.
        <em class="replaceable"><code>M</code></em> can range from 1 to 64.
      </p><p>
        To specify bit values,
        <code class="literal">b'<em class="replaceable"><code>value</code></em>'</code> notation
        can be used. <em class="replaceable"><code>value</code></em> is a binary value
        written using zeros and ones. For example,
        <code class="literal">b'111'</code> and <code class="literal">b'10000000'</code>
        represent 7 and 128, respectively. See
        <a class="xref" href="language-structure.html#bit-value-literals" title="9.1.5 Bit-Value Literals">Section 9.1.5, “Bit-Value Literals”</a>.
      </p><p>
        If you assign a value to a
        <code class="literal">BIT(<em class="replaceable"><code>M</code></em>)</code> column that
        is less than <em class="replaceable"><code>M</code></em> bits long, the value
        is padded on the left with zeros. For example, assigning a value
        of <code class="literal">b'101'</code> to a <code class="literal">BIT(6)</code>
        column is, in effect, the same as assigning
        <code class="literal">b'000101'</code>.
      </p><p><b>NDB Cluster. </b>
          The maximum combined size of all <code class="literal">BIT</code>
          columns used in a given <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> table
          must not exceed 4096 bits.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="numeric-type-attributes"></a>11.1.6 Numeric Type Attributes</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444338244112"></a><a class="indexterm" name="idm46444338243040"></a><a class="indexterm" name="idm46444338241968"></a><p>
        MySQL supports an extension for optionally specifying the
        display width of integer data types in parentheses following the
        base keyword for the type. For example,
        <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT(4)</code></a> specifies an
        <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a> with a display width of four
        digits. This optional display width may be used by applications
        to display integer values having a width less than the width
        specified for the column by left-padding them with spaces. (That
        is, this width is present in the metadata returned with result
        sets. Whether it is used is up to the application.)
      </p><p>
        The display width does <span class="emphasis"><em>not</em></span> constrain the
        range of values that can be stored in the column. Nor does it
        prevent values wider than the column display width from being
        displayed correctly. For example, a column specified as
        <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT(3)</code></a> has the usual
        <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a> range of
        <code class="literal">-32768</code> to <code class="literal">32767</code>, and
        values outside the range permitted by three digits are displayed
        in full using more than three digits.
      </p><p>
        When used in conjunction with the optional (nonstandard)
        <code class="literal">ZEROFILL</code> attribute, the default padding of
        spaces is replaced with zeros. For example, for a column
        declared as <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT(4) ZEROFILL</code></a>, a
        value of <code class="literal">5</code> is retrieved as
        <code class="literal">0005</code>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          The <code class="literal">ZEROFILL</code> attribute is ignored for
          columns involved in expressions or
          <a class="link" href="sql-statements.html#union" title="13.2.10.3 UNION Clause"><code class="literal">UNION</code></a> queries.
        </p><p>
          If you store values larger than the display width in an
          integer column that has the <code class="literal">ZEROFILL</code>
          attribute, you may experience problems when MySQL generates
          temporary tables for some complicated joins. In these cases,
          MySQL assumes that the data values fit within the column
          display width.
</p>
</div>
<p>
        As of MySQL 8.0.17, the <code class="literal">ZEROFILL</code> attribute is
        deprecated for numeric data types, as is the display width
        attribute for integer data types. Support for
        <code class="literal">ZEROFILL</code> and display widths for integer data
        types will be removed in a future MySQL version. Consider using
        an alternative means of producing the effect of these
        attributes. For example, applications could use the
        <a class="link" href="functions.html#function_lpad"><code class="literal">LPAD()</code></a> function to zero-pad
        numbers up to the desired width, or they could store the
        formatted numbers in <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>
        columns.
      </p><p>
        All integer types can have an optional (nonstandard)
        <code class="literal">UNSIGNED</code> attribute. An unsigned type can be
        used to permit only nonnegative numbers in a column or when you
        need a larger upper numeric range for the column. For example,
        if an <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a> column is
        <code class="literal">UNSIGNED</code>, the size of the column's range is
        the same but its endpoints shift up, from
        <code class="literal">-2147483648</code> and <code class="literal">2147483647</code>
        to <code class="literal">0</code> and <code class="literal">4294967295</code>.
      </p><p>
        Floating-point and fixed-point types also can be
        <code class="literal">UNSIGNED</code>. As with integer types, this
        attribute prevents negative values from being stored in the
        column. Unlike the integer types, the upper range of column
        values remains the same. As of MySQL 8.0.17, the
        <code class="literal">UNSIGNED</code> attribute is deprecated for columns
        of type <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a>,
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a>, and
        <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> (and any synonyms) and
        support for it will be removed in a future MySQL version.
        Consider using a simple <code class="literal">CHECK</code> constraint
        instead for such columns.
      </p><p>
        If you specify <code class="literal">ZEROFILL</code> for a numeric column,
        MySQL automatically adds the <code class="literal">UNSIGNED</code>
        attribute.
      </p><p>
        Integer or floating-point data types can have the
        <code class="literal">AUTO_INCREMENT</code> attribute. When you insert a
        value of <code class="literal">NULL</code> into an indexed
        <code class="literal">AUTO_INCREMENT</code> column, the column is set to
        the next sequence value. Typically this is
        <code class="literal"><em class="replaceable"><code>value</code></em>+1</code>, where
        <em class="replaceable"><code>value</code></em> is the largest value for the
        column currently in the table.
        (<code class="literal">AUTO_INCREMENT</code> sequences begin with
        <code class="literal">1</code>.)
      </p><p>
        Storing <code class="literal">0</code> into an
        <code class="literal">AUTO_INCREMENT</code> column has the same effect as
        storing <code class="literal">NULL</code>, unless the
        <a class="link" href="server-administration.html#sqlmode_no_auto_value_on_zero"><code class="literal">NO_AUTO_VALUE_ON_ZERO</code></a> SQL mode
        is enabled.
      </p><p>
        Inserting <code class="literal">NULL</code> to generate
        <code class="literal">AUTO_INCREMENT</code> values requires that the
        column be declared <code class="literal">NOT NULL</code>. If the column is
        declared <code class="literal">NULL</code>, inserting
        <code class="literal">NULL</code> stores a <code class="literal">NULL</code>. When
        you insert any other value into an
        <code class="literal">AUTO_INCREMENT</code> column, the column is set to
        that value and the sequence is reset so that the next
        automatically generated value follows sequentially from the
        inserted value.
      </p><p>
        Negative values for <code class="literal">AUTO_INCREMENT</code> columns
        are not supported.
      </p><p>
        <code class="literal">CHECK</code> constraints cannot refer to columns
        that have the <code class="literal">AUTO_INCREMENT</code> attribute, nor
        can the <code class="literal">AUTO_INCREMENT</code> attribute be added to
        existing columns that are used in <code class="literal">CHECK</code>
        constraints.
      </p><p>
        As of MySQL 8.0.17, <code class="literal">AUTO_INCREMENT</code> support is
        deprecated for <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a> and
        <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> columns and will be
        removed in a future MySQL version. Consider removing the
        <code class="literal">AUTO_INCREMENT</code> attribute from such columns,
        or convert them to an integer type.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="out-of-range-and-overflow"></a>11.1.7 Out-of-Range and Overflow Handling</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444338178944"></a><a class="indexterm" name="idm46444338177872"></a><p>
        When MySQL stores a value in a numeric column that is outside
        the permissible range of the column data type, the result
        depends on the SQL mode in effect at the time:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            If strict SQL mode is enabled, MySQL rejects the
            out-of-range value with an error, and the insert fails, in
            accordance with the SQL standard.
          </p></li><li class="listitem"><p>
            If no restrictive modes are enabled, MySQL clips the value
            to the appropriate endpoint of the column data type range
            and stores the resulting value instead.
          </p><p>
            When an out-of-range value is assigned to an integer column,
            MySQL stores the value representing the corresponding
            endpoint of the column data type range.
          </p><p>
            When a floating-point or fixed-point column is assigned a
            value that exceeds the range implied by the specified (or
            default) precision and scale, MySQL stores the value
            representing the corresponding endpoint of that range.
</p></li></ul>
</div>
<p>
        Suppose that a table <code class="literal">t1</code> has this definition:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (i1 TINYINT, i2 TINYINT UNSIGNED);</pre><p>
        With strict SQL mode enabled, an out of range error occurs:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET sql_mode = 'TRADITIONAL';</code></strong>
mysql&gt; <strong class="userinput"><code>INSERT INTO t1 (i1, i2) VALUES(256, 256);</code></strong>
ERROR 1264 (22003): Out of range value for column 'i1' at row 1
mysql&gt; <strong class="userinput"><code>SELECT * FROM t1;</code></strong>
Empty set (0.00 sec)
</pre><p>
        With strict SQL mode not enabled, clipping with warnings occurs:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET sql_mode = '';</code></strong>
mysql&gt; <strong class="userinput"><code>INSERT INTO t1 (i1, i2) VALUES(256, 256);</code></strong>
mysql&gt; <strong class="userinput"><code>SHOW WARNINGS;</code></strong>
+---------+------+---------------------------------------------+
| Level   | Code | Message                                     |
+---------+------+---------------------------------------------+
| Warning | 1264 | Out of range value for column 'i1' at row 1 |
| Warning | 1264 | Out of range value for column 'i2' at row 1 |
+---------+------+---------------------------------------------+
mysql&gt; <strong class="userinput"><code>SELECT * FROM t1;</code></strong>
+------+------+
| i1   | i2   |
+------+------+
|  127 |  255 |
+------+------+
</pre><p>
        When strict SQL mode is not enabled, column-assignment
        conversions that occur due to clipping are reported as warnings
        for <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>,
        <a class="link" href="sql-statements.html#load-data" title="13.2.7 LOAD DATA Statement"><code class="literal">LOAD DATA</code></a>,
        <a class="link" href="sql-statements.html#update" title="13.2.13 UPDATE Statement"><code class="literal">UPDATE</code></a>, and multiple-row
        <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a> statements. In strict
        mode, these statements fail, and some or all the values are not
        inserted or changed, depending on whether the table is a
        transactional table and other factors. For details, see
        <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><p>
        Overflow during numeric expression evaluation results in an
        error. For example, the largest signed
        <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a> value is
        9223372036854775807, so the following expression produces an
        error:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT 9223372036854775807 + 1;</code></strong>
ERROR 1690 (22003): BIGINT value is out of range in '(9223372036854775807 + 1)'
</pre><p>
        To enable the operation to succeed in this case, convert the
        value to unsigned;
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT CAST(9223372036854775807 AS UNSIGNED) + 1;</code></strong>
+-------------------------------------------+
| CAST(9223372036854775807 AS UNSIGNED) + 1 |
+-------------------------------------------+
|                       9223372036854775808 |
+-------------------------------------------+
</pre><p>
        Whether overflow occurs depends on the range of the operands, so
        another way to handle the preceding expression is to use
        exact-value arithmetic because
        <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> values have a larger
        range than integers:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT 9223372036854775807.0 + 1;</code></strong>
+---------------------------+
| 9223372036854775807.0 + 1 |
+---------------------------+
|     9223372036854775808.0 |
+---------------------------+
</pre><p>
        Subtraction between integer values, where one is of type
        <code class="literal">UNSIGNED</code>, produces an unsigned result by
        default. If the result would otherwise have been negative, an
        error results:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET sql_mode = '';</code></strong>
Query OK, 0 rows affected (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT CAST(0 AS UNSIGNED) - 1;</code></strong>
<span class="errortext">ERROR 1690 (22003): BIGINT UNSIGNED value is out of range in '(cast(0 as unsigned) - 1)'</span>
</pre><p>
        If the <a class="link" href="server-administration.html#sqlmode_no_unsigned_subtraction"><code class="literal">NO_UNSIGNED_SUBTRACTION</code></a>
        SQL mode is enabled, the result is negative:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT CAST(0 AS UNSIGNED) - 1;</code></strong>
+-------------------------+
| CAST(0 AS UNSIGNED) - 1 |
+-------------------------+
|                      -1 |
+-------------------------+
</pre><p>
        If the result of such an operation is used to update an
        <code class="literal">UNSIGNED</code> integer column, the result is
        clipped to the maximum value for the column type, or clipped to
        0 if <a class="link" href="server-administration.html#sqlmode_no_unsigned_subtraction"><code class="literal">NO_UNSIGNED_SUBTRACTION</code></a>
        is enabled. If strict SQL mode is enabled, an error occurs and
        the column remains unchanged.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="date-and-time-types"></a>11.2 Date and Time Data Types</h2>

</div>

</div>

</div>
<div class="toc">
<dl class="toc"><dt><span class="section"><a href="data-types.html#date-and-time-type-syntax">11.2.1 Date and Time Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#datetime">11.2.2 The DATE, DATETIME, and TIMESTAMP Types</a></span></dt><dt><span class="section"><a href="data-types.html#time">11.2.3 The TIME Type</a></span></dt><dt><span class="section"><a href="data-types.html#year">11.2.4 The YEAR Type</a></span></dt><dt><span class="section"><a href="data-types.html#timestamp-initialization">11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME</a></span></dt><dt><span class="section"><a href="data-types.html#fractional-seconds">11.2.6 Fractional Seconds in Time Values</a></span></dt><dt><span class="section"><a href="data-types.html#date-and-time-type-conversion">11.2.7 Conversion Between Date and Time Types</a></span></dt><dt><span class="section"><a href="data-types.html#two-digit-years">11.2.8 2-Digit Years in Dates</a></span></dt></dl>
</div>
<a class="indexterm" name="idm46444338133040"></a><a class="indexterm" name="idm46444338131584"></a><a class="indexterm" name="idm46444338130096"></a><p>
      The date and time data types for representing temporal values are
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>,
      <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>,
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>, and
      <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a>. Each temporal type has a
      range of valid values, as well as a <span class="quote">“<span class="quote">zero</span>”</span> value that
      may be used when you specify an invalid value that MySQL cannot
      represent. The <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> types have special
      automatic updating behavior, described in
      <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
    </p><p>
      For information about storage requirements of the temporal data
      types, see <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>.
    </p><p>
      For descriptions of functions that operate on temporal values, see
      <a class="xref" href="functions.html#date-and-time-functions" title="12.6 Date and Time Functions">Section 12.6, “Date and Time Functions”</a>.
    </p><p>
      Keep in mind these general considerations when working with date
      and time types:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          MySQL retrieves values for a given date or time type in a
          standard output format, but it attempts to interpret a variety
          of formats for input values that you supply (for example, when
          you specify a value to be assigned to or compared to a date or
          time type). For a description of the permitted formats for
          date and time types, see
          <a class="xref" href="language-structure.html#date-and-time-literals" title="9.1.3 Date and Time Literals">Section 9.1.3, “Date and Time Literals”</a>. It is expected that
          you supply valid values. Unpredictable results may occur if
          you use values in other formats.
        </p></li><li class="listitem"><p>
          Although MySQL tries to interpret values in several formats,
          date parts must always be given in year-month-day order (for
          example, <code class="literal">'98-09-04'</code>), rather than in the
          month-day-year or day-month-year orders commonly used
          elsewhere (for example, <code class="literal">'09-04-98'</code>,
          <code class="literal">'04-09-98'</code>). To convert strings in other
          orders to year-month-day order, the
          <a class="link" href="functions.html#function_str-to-date"><code class="literal">STR_TO_DATE()</code></a> function may be
          useful.
        </p></li><li class="listitem"><p>
          Dates containing 2-digit year values are ambiguous because the
          century is unknown. MySQL interprets 2-digit year values using
          these rules:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
              Year values in the range <code class="literal">70-99</code> become
              <code class="literal">1970-1999</code>.
            </p></li><li class="listitem"><p>
              Year values in the range <code class="literal">00-69</code> become
              <code class="literal">2000-2069</code>.
</p></li></ul>
</div>
<p>
          See also <a class="xref" href="data-types.html#two-digit-years" title="11.2.8 2-Digit Years in Dates">Section 11.2.8, “2-Digit Years in Dates”</a>.
        </p></li><li class="listitem"><p>
          Conversion of values from one temporal type to another occurs
          according to the rules in
          <a class="xref" href="data-types.html#date-and-time-type-conversion" title="11.2.7 Conversion Between Date and Time Types">Section 11.2.7, “Conversion Between Date and Time Types”</a>.
        </p></li><li class="listitem"><p>
          MySQL automatically converts a date or time value to a number
          if the value is used in numeric context and vice versa.
        </p></li><li class="listitem"><p>
          By default, when MySQL encounters a value for a date or time
          type that is out of range or otherwise invalid for the type,
          it converts the value to the <span class="quote">“<span class="quote">zero</span>”</span> value for
          that type. The exception is that out-of-range
          <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> values are clipped to the
          appropriate endpoint of the
          <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> range.
        </p></li><li class="listitem"><p>
          By setting the SQL mode to the appropriate value, you can
          specify more exactly what kind of dates you want MySQL to
          support. (See <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.) You can get MySQL
          to accept certain dates, such as
          <code class="literal">'2009-11-31'</code>, by enabling the
          <a class="link" href="server-administration.html#sqlmode_allow_invalid_dates"><code class="literal">ALLOW_INVALID_DATES</code></a> SQL
          mode. This is useful when you want to store a <span class="quote">“<span class="quote">possibly
          wrong</span>”</span> value which the user has specified (for example,
          in a web form) in the database for future processing. Under
          this mode, MySQL verifies only that the month is in the range
          from 1 to 12 and that the day is in the range from 1 to 31.
        </p></li><li class="listitem"><p>
          MySQL permits you to store dates where the day or month and
          day are zero in a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> or
          <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> column. This is useful
          for applications that need to store birthdates for which you
          may not know the exact date. In this case, you simply store
          the date as <code class="literal">'2009-00-00'</code> or
          <code class="literal">'2009-01-00'</code>. However, with dates such as
          these, you should not expect to get correct results for
          functions such as <a class="link" href="functions.html#function_date-sub"><code class="literal">DATE_SUB()</code></a> or
          <a class="link" href="functions.html#function_date-add"><code class="literal">DATE_ADD()</code></a> that require
          complete dates. To disallow zero month or day parts in dates,
          enable the <a class="link" href="server-administration.html#sqlmode_no_zero_in_date"><code class="literal">NO_ZERO_IN_DATE</code></a>
          mode.
        </p></li><li class="listitem"><p>
          MySQL permits you to store a <span class="quote">“<span class="quote">zero</span>”</span> value of
          <code class="literal">'0000-00-00'</code> as a <span class="quote">“<span class="quote">dummy
          date.</span>”</span> In some cases, this is more convenient than
          using <code class="literal">NULL</code> values, and uses less data and
          index space. To disallow <code class="literal">'0000-00-00'</code>,
          enable the <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a>
          mode.
        </p></li><li class="listitem"><p>
          <span class="quote">“<span class="quote">Zero</span>”</span> date or time values used through
          Connector/ODBC are converted automatically to
          <code class="literal">NULL</code> because ODBC cannot handle such
          values.
</p></li></ul>
</div>
<p>
      The following table shows the format of the <span class="quote">“<span class="quote">zero</span>”</span>
      value for each type. The <span class="quote">“<span class="quote">zero</span>”</span> values are special,
      but you can store or refer to them explicitly using the values
      shown in the table. You can also do this using the values
      <code class="literal">'0'</code> or <code class="literal">0</code>, which are easier
      to write. For temporal types that include a date part
      (<a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>,
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
      <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>), use of these values may
      produce warning or errors. The precise behavior depends on which,
      if any, of the strict and
      <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a> SQL modes are
      enabled; see <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
</p>
<div class="informaltable">
<table summary="Format of the zero value for temporal data types."><col width="30%"><col width="40%"><thead><tr>
          <th scope="col">Data Type</th>
          <th scope="col"><span class="quote">“<span class="quote">Zero</span>”</span> Value</th>
        </tr></thead><tbody><tr>
          <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a></td>
          <td><code class="literal">'0000-00-00'</code></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a></td>
          <td><code class="literal">'00:00:00'</code></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a></td>
          <td><code class="literal">'0000-00-00 00:00:00'</code></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a></td>
          <td><code class="literal">'0000-00-00 00:00:00'</code></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a></td>
          <td><code class="literal">0000</code></td>
</tr></tbody></table>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="date-and-time-type-syntax"></a>11.2.1 Date and Time Data Type Syntax</h3>

</div>

</div>

</div>
<p>
        The date and time data types for representing temporal values
        are <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>,
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>, and
        <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a>.
      </p><p>
        For the <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> range descriptions,
        <span class="quote">“<span class="quote">supported</span>”</span> means that although earlier values
        might work, there is no guarantee.
      </p><a class="indexterm" name="idm46444338030000"></a><a class="indexterm" name="idm46444338028912"></a><p>
        MySQL permits fractional seconds for
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values, with up to
        microseconds (6 digits) precision. To define a column that
        includes a fractional seconds part, use the syntax
        <code class="literal"><em class="replaceable"><code>type_name</code></em>(<em class="replaceable"><code>fsp</code></em>)</code>,
        where <em class="replaceable"><code>type_name</code></em> is
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>, and
        <em class="replaceable"><code>fsp</code></em> is the fractional seconds
        precision. For example:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (t TIME(3), dt DATETIME(6), ts TIMESTAMP(0));</pre><p>
        The <em class="replaceable"><code>fsp</code></em> value, if given, must be in
        the range 0 to 6. A value of 0 signifies that there is no
        fractional part. If omitted, the default precision is 0. (This
        differs from the standard SQL default of 6, for compatibility
        with previous MySQL versions.)
      </p><p>
        Any <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> column in a table can
        have automatic initialization and updating properties; see
        <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <a class="indexterm" name="idm46444338008624"></a>

            <a class="indexterm" name="idm46444338007552"></a>

            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>
          </p><p>
            A date. The supported range is
            <code class="literal">'1000-01-01'</code> to
            <code class="literal">'9999-12-31'</code>. MySQL displays
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> values in
            <code class="literal">'<em class="replaceable"><code>YYYY-MM-DD</code></em>'</code>
            format, but permits assignment of values to
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> columns using either
            strings or numbers.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337996656"></a>

            <a class="indexterm" name="idm46444337995584"></a>

            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME[(<em class="replaceable"><code>fsp</code></em>)]</code></a>
          </p><p>
            A date and time combination. The supported range is
            <code class="literal">'1000-01-01 00:00:00.000000'</code> to
            <code class="literal">'9999-12-31 23:59:59.999999'</code>. MySQL
            displays <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> values in
            <code class="literal">'<em class="replaceable"><code>YYYY-MM-DD
            hh:mm:ss</code></em>[.<em class="replaceable"><code>fraction</code></em>]'</code>
            format, but permits assignment of values to
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns using either
            strings or numbers.
          </p><p>
            An optional <em class="replaceable"><code>fsp</code></em> value in the
            range from 0 to 6 may be given to specify fractional seconds
            precision. A value of 0 signifies that there is no
            fractional part. If omitted, the default precision is 0.
          </p><p>
            Automatic initialization and updating to the current date
            and time for <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns
            can be specified using <code class="literal">DEFAULT</code> and
            <code class="literal">ON UPDATE</code> column definition clauses, as
            described in <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337978112"></a>

            <a class="indexterm" name="idm46444337977040"></a>

            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP[(<em class="replaceable"><code>fsp</code></em>)]</code></a>
          </p><a class="indexterm" name="idm46444337973840"></a><p>
            A timestamp. The range is <code class="literal">'1970-01-01
            00:00:01.000000'</code> UTC to <code class="literal">'2038-01-19
            03:14:07.999999'</code> UTC.
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values are stored
            as the number of seconds since the epoch
            (<code class="literal">'1970-01-01 00:00:00'</code> UTC). A
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> cannot represent
            the value <code class="literal">'1970-01-01 00:00:00'</code> because
            that is equivalent to 0 seconds from the epoch and the value
            0 is reserved for representing <code class="literal">'0000-00-00
            00:00:00'</code>, the <span class="quote">“<span class="quote">zero</span>”</span>
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> value.
          </p><p>
            An optional <em class="replaceable"><code>fsp</code></em> value in the
            range from 0 to 6 may be given to specify fractional seconds
            precision. A value of 0 signifies that there is no
            fractional part. If omitted, the default precision is 0.
          </p><p>
            The way the server handles <code class="literal">TIMESTAMP</code>
            definitions depends on the value of the
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            system variable (see
            <a class="xref" href="server-administration.html#server-system-variables" title="5.1.8 Server System Variables">Section 5.1.8, “Server System Variables”</a>).
          </p><p>
            If
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            is enabled, there is no automatic assignment of the
            <code class="literal">DEFAULT CURRENT_TIMESTAMP</code> or <code class="literal">ON
            UPDATE CURRENT_TIMESTAMP</code> attributes to any
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column. They must
            be included explicitly in the column definition. Also, any
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> not explicitly
            declared as <code class="literal">NOT NULL</code> permits
            <code class="literal">NULL</code> values.
          </p><p>
            If
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            is disabled, the server handles <code class="literal">TIMESTAMP</code>
            as follows:
          </p><p>
            Unless specified otherwise, the first
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column in a table
            is defined to be automatically set to the date and time of
            the most recent modification if not explicitly assigned a
            value. This makes <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>
            useful for recording the timestamp of an
            <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a> or
            <a class="link" href="sql-statements.html#update" title="13.2.13 UPDATE Statement"><code class="literal">UPDATE</code></a> operation. You can
            also set any <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column
            to the current date and time by assigning it a
            <code class="literal">NULL</code> value, unless it has been defined
            with the <code class="literal">NULL</code> attribute to permit
            <code class="literal">NULL</code> values.
          </p><p>
            Automatic initialization and updating to the current date
            and time can be specified using <code class="literal">DEFAULT
            CURRENT_TIMESTAMP</code> and <code class="literal">ON UPDATE
            CURRENT_TIMESTAMP</code> column definition clauses. By
            default, the first <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>
            column has these properties, as previously noted. However,
            any <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column in a
            table can be defined to have these properties.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337933312"></a>

            <a class="indexterm" name="idm46444337932240"></a>

            <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME[(<em class="replaceable"><code>fsp</code></em>)]</code></a>
          </p><p>
            A time. The range is <code class="literal">'-838:59:59.000000'</code>
            to <code class="literal">'838:59:59.000000'</code>. MySQL displays
            <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> values in
            <code class="literal">'<em class="replaceable"><code>hh:mm:ss</code></em>[.<em class="replaceable"><code>fraction</code></em>]'</code>
            format, but permits assignment of values to
            <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> columns using either
            strings or numbers.
          </p><p>
            An optional <em class="replaceable"><code>fsp</code></em> value in the
            range from 0 to 6 may be given to specify fractional seconds
            precision. A value of 0 signifies that there is no
            fractional part. If omitted, the default precision is 0.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337919520"></a>

            <a class="indexterm" name="idm46444337918448"></a>

            <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR[(4)]</code></a>
          </p><p>
            A year in 4-digit format. MySQL displays
            <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> values in
            <em class="replaceable"><code>YYYY</code></em> format, but permits
            assignment of values to <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a>
            columns using either strings or numbers. Values display as
            <code class="literal">1901</code> to <code class="literal">2155</code>, or
            <code class="literal">0000</code>.
          </p><p>
            For additional information about
            <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> display format and
            interpretation of input values, see <a class="xref" href="data-types.html#year" title="11.2.4 The YEAR Type">Section 11.2.4, “The YEAR Type”</a>.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
              As of MySQL 8.0.19, the
              <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR(4)</code></a> data type with an
              explicit display width is deprecated and support for it
              will be removed in a future MySQL version. Instead, use
              <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> without a display
              width, which has the same meaning.
            </p><p>
              MySQL 8.0 does not support the 2-digit
              <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR(2)</code></a> data type permitted
              in older versions of MySQL. For instructions on converting
              to 4-digit <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a>, see
              <a class="ulink" href="https://dev.mysql.com/doc/refman/5.7/en/migrating-from-year2.html" target="_top">2-Digit YEAR(2) Limitations and Migrating to 4-Digit YEAR</a> in
              <a class="ulink" href="https://dev.mysql.com/doc/refman/5.7/en/" target="_top">MySQL 5.7 Reference Manual</a>.
</p>
</div>
</li></ul>
</div>
<p>
        The <a class="link" href="functions.html#function_sum"><code class="literal">SUM()</code></a> and
        <a class="link" href="functions.html#function_avg"><code class="literal">AVG()</code></a> aggregate functions do not
        work with temporal values. (They convert the values to numbers,
        losing everything after the first nonnumeric character.) To work
        around this problem, convert to numeric units, perform the
        aggregate operation, and convert back to a temporal value.
        Examples:
      </p><pre data-lang="sql" class="programlisting">SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(<em class="replaceable"><code>time_col</code></em>))) FROM <em class="replaceable"><code>tbl_name</code></em>;
SELECT FROM_DAYS(SUM(TO_DAYS(<em class="replaceable"><code>date_col</code></em>))) FROM <em class="replaceable"><code>tbl_name</code></em>;
</pre>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="datetime"></a>11.2.2 The DATE, DATETIME, and TIMESTAMP Types</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444337891456"></a><a class="indexterm" name="idm46444337890416"></a><a class="indexterm" name="idm46444337889344"></a><a class="indexterm" name="idm46444337888272"></a><a class="indexterm" name="idm46444337886784"></a><a class="indexterm" name="idm46444337885296"></a><p>
        The <code class="literal">DATE</code>, <code class="literal">DATETIME</code>, and
        <code class="literal">TIMESTAMP</code> types are related. This section
        describes their characteristics, how they are similar, and how
        they differ. MySQL recognizes <code class="literal">DATE</code>,
        <code class="literal">DATETIME</code>, and <code class="literal">TIMESTAMP</code>
        values in several formats, described in
        <a class="xref" href="language-structure.html#date-and-time-literals" title="9.1.3 Date and Time Literals">Section 9.1.3, “Date and Time Literals”</a>. For the
        <code class="literal">DATE</code> and <code class="literal">DATETIME</code> range
        descriptions, <span class="quote">“<span class="quote">supported</span>”</span> means that although
        earlier values might work, there is no guarantee.
      </p><p>
        The <code class="literal">DATE</code> type is used for values with a date
        part but no time part. MySQL retrieves and displays
        <code class="literal">DATE</code> values in
        <code class="literal">'<em class="replaceable"><code>YYYY-MM-DD</code></em>'</code>
        format. The supported range is <code class="literal">'1000-01-01'</code>
        to <code class="literal">'9999-12-31'</code>.
      </p><p>
        The <code class="literal">DATETIME</code> type is used for values that
        contain both date and time parts. MySQL retrieves and displays
        <code class="literal">DATETIME</code> values in
        <code class="literal">'<em class="replaceable"><code>YYYY-MM-DD
        hh:mm:ss</code></em>'</code> format. The supported range is
        <code class="literal">'1000-01-01 00:00:00'</code> to <code class="literal">'9999-12-31
        23:59:59'</code>.
      </p><p>
        The <code class="literal">TIMESTAMP</code> data type is used for values
        that contain both date and time parts.
        <code class="literal">TIMESTAMP</code> has a range of <code class="literal">'1970-01-01
        00:00:01'</code> UTC to <code class="literal">'2038-01-19
        03:14:07'</code> UTC.
      </p><p>
        A <code class="literal">DATETIME</code> or <code class="literal">TIMESTAMP</code>
        value can include a trailing fractional seconds part in up to
        microseconds (6 digits) precision. In particular, any fractional
        part in a value inserted into a <code class="literal">DATETIME</code> or
        <code class="literal">TIMESTAMP</code> column is stored rather than
        discarded. With the fractional part included, the format for
        these values is <code class="literal">'<em class="replaceable"><code>YYYY-MM-DD
        hh:mm:ss</code></em>[.<em class="replaceable"><code>fraction</code></em>]'</code>,
        the range for <code class="literal">DATETIME</code> values is
        <code class="literal">'1000-01-01 00:00:00.000000'</code> to
        <code class="literal">'9999-12-31 23:59:59.999999'</code>, and the range
        for <code class="literal">TIMESTAMP</code> values is <code class="literal">'1970-01-01
        00:00:01.000000'</code> to <code class="literal">'2038-01-19
        03:14:07.999999'</code>. The fractional part should always be
        separated from the rest of the time by a decimal point; no other
        fractional seconds delimiter is recognized. For information
        about fractional seconds support in MySQL, see
        <a class="xref" href="data-types.html#fractional-seconds" title="11.2.6 Fractional Seconds in Time Values">Section 11.2.6, “Fractional Seconds in Time Values”</a>.
      </p><p>
        The <code class="literal">TIMESTAMP</code> and <code class="literal">DATETIME</code>
        data types offer automatic initialization and updating to the
        current date and time. For more information, see
        <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
      </p><p>
        MySQL converts <code class="literal">TIMESTAMP</code> values from the
        current time zone to UTC for storage, and back from UTC to the
        current time zone for retrieval. (This does not occur for other
        types such as <code class="literal">DATETIME</code>.) By default, the
        current time zone for each connection is the server's time. The
        time zone can be set on a per-connection basis. As long as the
        time zone setting remains constant, you get back the same value
        you store. If you store a <code class="literal">TIMESTAMP</code> value,
        and then change the time zone and retrieve the value, the
        retrieved value is different from the value you stored. This
        occurs because the same time zone was not used for conversion in
        both directions. The current time zone is available as the value
        of the <a class="link" href="server-administration.html#sysvar_time_zone"><code class="literal">time_zone</code></a> system
        variable. For more information, see
        <a class="xref" href="server-administration.html#time-zone-support" title="5.1.14 MySQL Server Time Zone Support">Section 5.1.14, “MySQL Server Time Zone Support”</a>.
      </p><p>
        As of MySQL 8.0.19, you can specify a time zone offset when
        inserting <code class="literal">TIMESTAMP</code> and
        <code class="literal">DATETIME</code> values into a table. The offset is
        appended to the date part of a datetime literal, with no
        intravening spaces, and uses the same format used for setting
        the <a class="link" href="server-administration.html#sysvar_time_zone"><code class="literal">time_zone</code></a> system variable,
        with the following exceptions:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            For hour values less than than 10, a leading zero is
            required.
          </p></li><li class="listitem"><p>
            The value <code class="literal">'-00:00'</code> is rejected.
          </p></li><li class="listitem"><p>
            Time zone names such as <code class="literal">'EET'</code> and
            <code class="literal">'Asia/Shanghai'</code> cannot be used;
            <code class="literal">'SYSTEM'</code> also cannot be used in this
            context.
</p></li></ul>
</div>
<p>
        This example illustrates inserting datetime values with time
        zone offsets into <code class="literal">TIMESTAMP</code> and
        <code class="literal">DATETIME</code> columns using different
        <a class="link" href="server-administration.html#sysvar_time_zone"><code class="literal">time_zone</code></a> settings, and then
        retrieving them:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE ts (</code></strong>
    -&gt;     <strong class="userinput"><code>id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,</code></strong>
    -&gt;     <strong class="userinput"><code>col TIMESTAMP NOT NULL</code></strong>
    -&gt; <strong class="userinput"><code>) AUTO_INCREMENT = 1;</code></strong>

mysql&gt; <strong class="userinput"><code>CREATE TABLE dt (</code></strong>
    -&gt;     <strong class="userinput"><code>id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,</code></strong>
    -&gt;     <strong class="userinput"><code>col DATETIME NOT NULL</code></strong>
    -&gt; <strong class="userinput"><code>) AUTO_INCREMENT = 1;</code></strong>
 
mysql&gt; <strong class="userinput"><code>SET @@time_zone = 'SYSTEM';</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO ts (col) VALUES ('2020-01-01 10:10:10'),</code></strong>
    -&gt;     <strong class="userinput"><code>('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');</code></strong>
 
mysql&gt; <strong class="userinput"><code>SET @@time_zone = '+00:00';</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO ts (col) VALUES ('2020-01-01 10:10:10'),</code></strong>
    -&gt;     <strong class="userinput"><code>('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');</code></strong>
 
mysql&gt; <strong class="userinput"><code>SET @@time_zone = 'SYSTEM';</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO dt (col) VALUES ('2020-01-01 10:10:10'),</code></strong>
    -&gt;     <strong class="userinput"><code>('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');</code></strong>
 
mysql&gt; <strong class="userinput"><code>SET @@time_zone = '+00:00';</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO dt (col) VALUES ('2020-01-01 10:10:10'),</code></strong>
    -&gt;     <strong class="userinput"><code>('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');</code></strong>
 
mysql&gt; <strong class="userinput"><code>SET @@time_zone = 'SYSTEM';</code></strong>

mysql&gt; <strong class="userinput"><code>SELECT @@system_time_zone;</code></strong>
+--------------------+
| @@system_time_zone |
+--------------------+
| EST                |
+--------------------+

mysql&gt; <strong class="userinput"><code>SELECT col, UNIX_TIMESTAMP(col) FROM dt ORDER BY id;</code></strong>
+---------------------+---------------------+
| col                 | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 |          1577891410 |
| 2019-12-31 23:40:10 |          1577853610 |
| 2020-01-01 13:10:10 |          1577902210 |
| 2020-01-01 10:10:10 |          1577891410 |
| 2020-01-01 04:40:10 |          1577871610 |
| 2020-01-01 18:10:10 |          1577920210 |
+---------------------+---------------------+

mysql&gt; <strong class="userinput"><code>SELECT col, UNIX_TIMESTAMP(col) FROM ts ORDER BY id;</code></strong>
+---------------------+---------------------+
| col                 | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 |          1577891410 |
| 2019-12-31 23:40:10 |          1577853610 |
| 2020-01-01 13:10:10 |          1577902210 |
| 2020-01-01 05:10:10 |          1577873410 |
| 2019-12-31 23:40:10 |          1577853610 |
| 2020-01-01 13:10:10 |          1577902210 |
+---------------------+---------------------+
</pre><p>
        The offset is not displayed when selecting a datetime value,
        even if one was used when inserting it.
      </p><p>
        The range of supported offset values is
        <code class="literal">-14:00</code> to <code class="literal">+14:00</code>,
        inclusive.
      </p><p>
        Datetime literals that include time zone offsets are accepted as
        parameter values by prepared statements.
      </p><p>
        Invalid <code class="literal">DATE</code>, <code class="literal">DATETIME</code>, or
        <code class="literal">TIMESTAMP</code> values are converted to the
        <span class="quote">“<span class="quote">zero</span>”</span> value of the appropriate type
        (<code class="literal">'0000-00-00'</code> or <code class="literal">'0000-00-00
        00:00:00'</code>), if the SQL mode permits this conversion.
        The precise behavior depends on which if any of strict SQL mode
        and the <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a> SQL mode
        are enabled; see <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><a class="indexterm" name="idm46444337803168"></a><a class="indexterm" name="idm46444337801680"></a><p>
        Be aware of certain properties of date value interpretation in
        MySQL:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            MySQL permits a <span class="quote">“<span class="quote">relaxed</span>”</span> format for values
            specified as strings, in which any punctuation character may
            be used as the delimiter between date parts or time parts.
            In some cases, this syntax can be deceiving. For example, a
            value such as <code class="literal">'10:11:12'</code> might look like
            a time value because of the <code class="literal">:</code>, but is
            interpreted as the year <code class="literal">'2010-11-12'</code> if
            used in date context. The value
            <code class="literal">'10:45:15'</code> is converted to
            <code class="literal">'0000-00-00'</code> because
            <code class="literal">'45'</code> is not a valid month.
          </p><p>
            The only delimiter recognized between a date and time part
            and a fractional seconds part is the decimal point.
          </p></li><li class="listitem"><p>
            The server requires that month and day values be valid, and
            not merely in the range 1 to 12 and 1 to 31, respectively.
            With strict mode disabled, invalid dates such as
            <code class="literal">'2004-04-31'</code> are converted to
            <code class="literal">'0000-00-00'</code> and a warning is generated.
            With strict mode enabled, invalid dates generate an error.
            To permit such dates, enable
            <a class="link" href="server-administration.html#sqlmode_allow_invalid_dates"><code class="literal">ALLOW_INVALID_DATES</code></a>. See
            <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>, for more information.
          </p></li><li class="listitem"><p>
            MySQL does not accept <code class="literal">TIMESTAMP</code> values
            that include a zero in the day or month column or values
            that are not a valid date. The sole exception to this rule
            is the special <span class="quote">“<span class="quote">zero</span>”</span> value
            <code class="literal">'0000-00-00 00:00:00'</code>, if the SQL mode
            permits this value. The precise behavior depends on which if
            any of strict SQL mode and the
            <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a> SQL mode are
            enabled; see <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
          </p></li><li class="listitem"><p>
            Dates containing 2-digit year values are ambiguous because
            the century is unknown. MySQL interprets 2-digit year values
            using these rules:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                Year values in the range <code class="literal">00-69</code> become
                <code class="literal">2000-2069</code>.
              </p></li><li class="listitem"><p>
                Year values in the range <code class="literal">70-99</code> become
                <code class="literal">1970-1999</code>.
</p></li></ul>
</div>
<p>
            See also <a class="xref" href="data-types.html#two-digit-years" title="11.2.8 2-Digit Years in Dates">Section 11.2.8, “2-Digit Years in Dates”</a>.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="time"></a>11.2.3 The TIME Type</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444337775152"></a><a class="indexterm" name="idm46444337774080"></a><p>
        MySQL retrieves and displays <code class="literal">TIME</code> values in
        <em class="replaceable"><code>'hh:mm:ss'</code></em> format (or
        <em class="replaceable"><code>'hhh:mm:ss'</code></em> format for large hours
        values). <code class="literal">TIME</code> values may range from
        <code class="literal">'-838:59:59'</code> to
        <code class="literal">'838:59:59'</code>. The hours part may be so large
        because the <code class="literal">TIME</code> type can be used not only to
        represent a time of day (which must be less than 24 hours), but
        also elapsed time or a time interval between two events (which
        may be much greater than 24 hours, or even negative).
      </p><p>
        MySQL recognizes <code class="literal">TIME</code> values in several
        formats, some of which can include a trailing fractional seconds
        part in up to microseconds (6 digits) precision. See
        <a class="xref" href="language-structure.html#date-and-time-literals" title="9.1.3 Date and Time Literals">Section 9.1.3, “Date and Time Literals”</a>. For information about
        fractional seconds support in MySQL, see
        <a class="xref" href="data-types.html#fractional-seconds" title="11.2.6 Fractional Seconds in Time Values">Section 11.2.6, “Fractional Seconds in Time Values”</a>. In particular, any
        fractional part in a value inserted into a
        <code class="literal">TIME</code> column is stored rather than discarded.
        With the fractional part included, the range for
        <code class="literal">TIME</code> values is
        <code class="literal">'-838:59:59.000000'</code> to
        <code class="literal">'838:59:59.000000'</code>.
      </p><p>
        Be careful about assigning abbreviated values to a
        <code class="literal">TIME</code> column. MySQL interprets abbreviated
        <code class="literal">TIME</code> values with colons as time of the day.
        That is, <code class="literal">'11:12'</code> means
        <code class="literal">'11:12:00'</code>, not
        <code class="literal">'00:11:12'</code>. MySQL interprets abbreviated
        values without colons using the assumption that the two
        rightmost digits represent seconds (that is, as elapsed time
        rather than as time of day). For example, you might think of
        <code class="literal">'1112'</code> and <code class="literal">1112</code> as meaning
        <code class="literal">'11:12:00'</code> (12 minutes after 11 o'clock), but
        MySQL interprets them as <code class="literal">'00:11:12'</code> (11
        minutes, 12 seconds). Similarly, <code class="literal">'12'</code> and
        <code class="literal">12</code> are interpreted as
        <code class="literal">'00:00:12'</code>.
      </p><p>
        The only delimiter recognized between a time part and a
        fractional seconds part is the decimal point.
      </p><p>
        By default, values that lie outside the <code class="literal">TIME</code>
        range but are otherwise valid are clipped to the closest
        endpoint of the range. For example,
        <code class="literal">'-850:00:00'</code> and
        <code class="literal">'850:00:00'</code> are converted to
        <code class="literal">'-838:59:59'</code> and
        <code class="literal">'838:59:59'</code>. Invalid <code class="literal">TIME</code>
        values are converted to <code class="literal">'00:00:00'</code>. Note that
        because <code class="literal">'00:00:00'</code> is itself a valid
        <code class="literal">TIME</code> value, there is no way to tell, from a
        value of <code class="literal">'00:00:00'</code> stored in a table,
        whether the original value was specified as
        <code class="literal">'00:00:00'</code> or whether it was invalid.
      </p><p>
        For more restrictive treatment of invalid
        <code class="literal">TIME</code> values, enable strict SQL mode to cause
        errors to occur. See <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="year"></a>11.2.4 The YEAR Type</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444337739824"></a><a class="indexterm" name="idm46444337738752"></a><p>
        The <code class="literal">YEAR</code> type is a 1-byte type used to
        represent year values. It can be declared as
        <code class="literal">YEAR</code> with an implicit display width of 4
        characters, or equivalently as <code class="literal">YEAR(4)</code> with
        an explicit display width.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          As of MySQL 8.0.19, the <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR(4)</code></a>
          data type with an explicit display width is deprecated and
          support for it will be removed in a future MySQL version.
          Instead, use <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> without a
          display width, which has the same meaning.
        </p><p>
          MySQL 8.0 does not support the 2-digit
          <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR(2)</code></a> data type permitted in
          older versions of MySQL. For instructions on converting to
          4-digit <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a>, see
          <a class="ulink" href="https://dev.mysql.com/doc/refman/5.7/en/migrating-from-year2.html" target="_top">2-Digit YEAR(2) Limitations and Migrating to 4-Digit YEAR</a> in
          <a class="ulink" href="https://dev.mysql.com/doc/refman/5.7/en/" target="_top">MySQL 5.7 Reference Manual</a>.
</p>
</div>
<p>
        MySQL displays <code class="literal">YEAR</code> values in
        <em class="replaceable"><code>YYYY</code></em> format, with a range of
        <code class="literal">1901</code> to <code class="literal">2155</code>, and
        <code class="literal">0000</code>.
      </p><p>
        <code class="literal">YEAR</code> accepts input values in a variety of
        formats:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            As 4-digit strings in the range <code class="literal">'1901'</code> to
            <code class="literal">'2155'</code>.
          </p></li><li class="listitem"><p>
            As 4-digit numbers in the range <code class="literal">1901</code> to
            <code class="literal">2155</code>.
          </p></li><li class="listitem"><p>
            As 1- or 2-digit strings in the range <code class="literal">'0'</code>
            to <code class="literal">'99'</code>. MySQL converts values in the
            ranges <code class="literal">'0'</code> to <code class="literal">'69'</code> and
            <code class="literal">'70'</code> to <code class="literal">'99'</code> to
            <code class="literal">YEAR</code> values in the ranges
            <code class="literal">2000</code> to <code class="literal">2069</code> and
            <code class="literal">1970</code> to <code class="literal">1999</code>.
          </p></li><li class="listitem"><p>
            As 1- or 2-digit numbers in the range <code class="literal">0</code>
            to <code class="literal">99</code>. MySQL converts values in the
            ranges <code class="literal">1</code> to <code class="literal">69</code> and
            <code class="literal">70</code> to <code class="literal">99</code> to
            <code class="literal">YEAR</code> values in the ranges
            <code class="literal">2001</code> to <code class="literal">2069</code> and
            <code class="literal">1970</code> to <code class="literal">1999</code>.
          </p><p>
            The result of inserting a numeric <code class="literal">0</code> has a
            display value of <code class="literal">0000</code> and an internal
            value of <code class="literal">0000</code>. To insert zero and have it
            be interpreted as <code class="literal">2000</code>, specify it as a
            string <code class="literal">'0'</code> or <code class="literal">'00'</code>.
          </p></li><li class="listitem"><p>
            As the result of functions that return a value that is
            acceptable in <code class="literal">YEAR</code> context, such as
            <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a>.
</p></li></ul>
</div>
<p>
        If strict SQL mode is not enabled, MySQL converts invalid
        <code class="literal">YEAR</code> values to <code class="literal">0000</code>. In
        strict SQL mode, attempting to insert an invalid
        <code class="literal">YEAR</code> value produces an error.
      </p><p>
        See also <a class="xref" href="data-types.html#two-digit-years" title="11.2.8 2-Digit Years in Dates">Section 11.2.8, “2-Digit Years in Dates”</a>.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="timestamp-initialization"></a>11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444337686320"></a><p>
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns can be
        automatically initializated and updated to the current date and
        time (that is, the current timestamp).
      </p><p>
        For any <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> column in a table, you
        can assign the current timestamp as the default value, the
        auto-update value, or both:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            An auto-initialized column is set to the current timestamp
            for inserted rows that specify no value for the column.
          </p></li><li class="listitem"><p>
            An auto-updated column is automatically updated to the
            current timestamp when the value of any other column in the
            row is changed from its current value. An auto-updated
            column remains unchanged if all other columns are set to
            their current values. To prevent an auto-updated column from
            updating when other columns change, explicitly set it to its
            current value. To update an auto-updated column even when
            other columns do not change, explicitly set it to the value
            it should have (for example, set it to
            <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a>).
</p></li></ul>
</div>
<p>
        In addition, if the
        <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
        system variable is disabled, you can initialize or update any
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> (but not
        <code class="literal">DATETIME</code>) column to the current date and time
        by assigning it a <code class="literal">NULL</code> value, unless it has
        been defined with the <code class="literal">NULL</code> attribute to
        permit <code class="literal">NULL</code> values.
      </p><p>
        To specify automatic properties, use the <code class="literal">DEFAULT
        CURRENT_TIMESTAMP</code> and <code class="literal">ON UPDATE
        CURRENT_TIMESTAMP</code> clauses in column definitions. The
        order of the clauses does not matter. If both are present in a
        column definition, either can occur first. Any of the synonyms
        for <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> have the
        same meaning as
        <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a>. These are
        <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP()</code></a>,
        <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a>,
        <a class="link" href="functions.html#function_localtime"><code class="literal">LOCALTIME</code></a>,
        <a class="link" href="functions.html#function_localtime"><code class="literal">LOCALTIME()</code></a>,
        <a class="link" href="functions.html#function_localtimestamp"><code class="literal">LOCALTIMESTAMP</code></a>, and
        <a class="link" href="functions.html#function_localtimestamp"><code class="literal">LOCALTIMESTAMP()</code></a>.
      </p><p>
        Use of <code class="literal">DEFAULT CURRENT_TIMESTAMP</code> and
        <code class="literal">ON UPDATE CURRENT_TIMESTAMP</code> is specific to
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>. The
        <code class="literal">DEFAULT</code> clause also can be used to specify a
        constant (nonautomatic) default value (for example,
        <code class="literal">DEFAULT 0</code> or <code class="literal">DEFAULT '2000-01-01
        00:00:00'</code>).
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          The following examples use <code class="literal">DEFAULT 0</code>, a
          default that can produce warnings or errors depending on
          whether strict SQL mode or the
          <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a> SQL mode is
          enabled. Be aware that the
          <a class="link" href="server-administration.html#sqlmode_traditional"><code class="literal">TRADITIONAL</code></a> SQL mode
          includes strict mode and
          <a class="link" href="server-administration.html#sqlmode_no_zero_date"><code class="literal">NO_ZERO_DATE</code></a>. See
          <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
</p>
</div>
<p>
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> column definitions can
        specify the current timestamp for both the default and
        auto-update values, for one but not the other, or for neither.
        Different columns can have different combinations of automatic
        properties. The following rules describe the possibilities:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            With both <code class="literal">DEFAULT CURRENT_TIMESTAMP</code> and
            <code class="literal">ON UPDATE CURRENT_TIMESTAMP</code>, the column
            has the current timestamp for its default value and is
            automatically updated to the current timestamp.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  dt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);</pre></li><li class="listitem"><p>
            With a <code class="literal">DEFAULT</code> clause but no <code class="literal">ON
            UPDATE CURRENT_TIMESTAMP</code> clause, the column has
            the given default value and is not automatically updated to
            the current timestamp.
          </p><p>
            The default depends on whether the
            <code class="literal">DEFAULT</code> clause specifies
            <code class="literal">CURRENT_TIMESTAMP</code> or a constant value.
            With <code class="literal">CURRENT_TIMESTAMP</code>, the default is
            the current timestamp.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  dt DATETIME DEFAULT CURRENT_TIMESTAMP
);</pre><p>
            With a constant, the default is the given value. In this
            case, the column has no automatic properties at all.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT 0,
  dt DATETIME DEFAULT 0
);</pre></li><li class="listitem"><p>
            With an <code class="literal">ON UPDATE CURRENT_TIMESTAMP</code>
            clause and a constant <code class="literal">DEFAULT</code> clause, the
            column is automatically updated to the current timestamp and
            has the given constant default value.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP,
  dt DATETIME DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
);</pre></li><li class="listitem"><p>
            With an <code class="literal">ON UPDATE CURRENT_TIMESTAMP</code>
            clause but no <code class="literal">DEFAULT</code> clause, the column
            is automatically updated to the current timestamp but does
            not have the current timestamp for its default value.
          </p><p>
            The default in this case is type dependent.
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> has a default of 0
            unless defined with the <code class="literal">NULL</code> attribute,
            in which case the default is <code class="literal">NULL</code>.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts1 TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,     -- default 0
  ts2 TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP -- default NULL
);</pre><p>
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> has a default of
            <code class="literal">NULL</code> unless defined with the <code class="literal">NOT
            NULL</code> attribute, in which case the default is 0.
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  dt1 DATETIME ON UPDATE CURRENT_TIMESTAMP,         -- default NULL
  dt2 DATETIME NOT NULL ON UPDATE CURRENT_TIMESTAMP -- default 0
);</pre></li></ul>
</div>
<p>
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns have no
        automatic properties unless they are specified explicitly, with
        this exception: If the
        <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
        system variable is disabled, the <span class="emphasis"><em>first</em></span>
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column has both
        <code class="literal">DEFAULT CURRENT_TIMESTAMP</code> and <code class="literal">ON
        UPDATE CURRENT_TIMESTAMP</code> if neither is specified
        explicitly. To suppress automatic properties for the first
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column, use one of
        these strategies:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Enable the
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            system variable. In this case, the <code class="literal">DEFAULT
            CURRENT_TIMESTAMP</code> and <code class="literal">ON UPDATE
            CURRENT_TIMESTAMP</code> clauses that specify automatic
            initialization and updating are available, but are not
            assigned to any <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>
            column unless explicitly included in the column definition.
          </p></li><li class="listitem"><p>
            Alternatively, if
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            is disabled, do either of the following:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                Define the column with a <code class="literal">DEFAULT</code>
                clause that specifies a constant default value.
              </p></li><li class="listitem"><p>
                Specify the <code class="literal">NULL</code> attribute. This also
                causes the column to permit <code class="literal">NULL</code>
                values, which means that you cannot assign the current
                timestamp by setting the column to
                <code class="literal">NULL</code>. Assigning
                <code class="literal">NULL</code> sets the column to
                <code class="literal">NULL</code>, not the current timestamp. To
                assign the current timestamp, set the column to
                <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> or a
                synonym such as <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a>.
</p></li></ul>
</div>
</li></ul>
</div>
<p>
        Consider these table definitions:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts1 TIMESTAMP DEFAULT 0,
  ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ON UPDATE CURRENT_TIMESTAMP);
CREATE TABLE t2 (
  ts1 TIMESTAMP NULL,
  ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ON UPDATE CURRENT_TIMESTAMP);
CREATE TABLE t3 (
  ts1 TIMESTAMP NULL DEFAULT 0,
  ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                ON UPDATE CURRENT_TIMESTAMP);</pre><p>
        The tables have these properties:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            In each table definition, the first
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column has no
            automatic initialization or updating.
          </p></li><li class="listitem"><p>
            The tables differ in how the <code class="literal">ts1</code> column
            handles <code class="literal">NULL</code> values. For
            <code class="literal">t1</code>, <code class="literal">ts1</code> is
            <code class="literal">NOT NULL</code> and assigning it a value of
            <code class="literal">NULL</code> sets it to the current timestamp.
            For <code class="literal">t2</code> and <code class="literal">t3</code>,
            <code class="literal">ts1</code> permits <code class="literal">NULL</code> and
            assigning it a value of <code class="literal">NULL</code> sets it to
            <code class="literal">NULL</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">t2</code> and <code class="literal">t3</code> differ in
            the default value for <code class="literal">ts1</code>. For
            <code class="literal">t2</code>, <code class="literal">ts1</code> is defined to
            permit <code class="literal">NULL</code>, so the default is also
            <code class="literal">NULL</code> in the absence of an explicit
            <code class="literal">DEFAULT</code> clause. For
            <code class="literal">t3</code>, <code class="literal">ts1</code> permits
            <code class="literal">NULL</code> but has an explicit default of 0.
</p></li></ul>
</div>
<p>
        If a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> column definition
        includes an explicit fractional seconds precision value
        anywhere, the same value must be used throughout the column
        definition. This is permitted:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
);</pre><p>
        This is not permitted:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(3)
);</pre>
<h4><a name="idm46444337560448"></a>TIMESTAMP Initialization and the NULL Attribute</h4>
<p>
        If the
        <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
        system variable is disabled,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> columns by default are
        <code class="literal">NOT NULL</code>, cannot contain
        <code class="literal">NULL</code> values, and assigning
        <code class="literal">NULL</code> assigns the current timestamp. To permit
        a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column to contain
        <code class="literal">NULL</code>, explicitly declare it with the
        <code class="literal">NULL</code> attribute. In this case, the default
        value also becomes <code class="literal">NULL</code> unless overridden
        with a <code class="literal">DEFAULT</code> clause that specifies a
        different default value. <code class="literal">DEFAULT NULL</code> can be
        used to explicitly specify <code class="literal">NULL</code> as the
        default value. (For a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>
        column not declared with the <code class="literal">NULL</code> attribute,
        <code class="literal">DEFAULT NULL</code> is invalid.) If a
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column permits
        <code class="literal">NULL</code> values, assigning
        <code class="literal">NULL</code> sets it to <code class="literal">NULL</code>, not
        to the current timestamp.
      </p><p>
        The following table contains several
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> columns that permit
        <code class="literal">NULL</code> values:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t
(
  ts1 TIMESTAMP NULL DEFAULT NULL,
  ts2 TIMESTAMP NULL DEFAULT 0,
  ts3 TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
);</pre><p>
        A <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column that permits
        <code class="literal">NULL</code> values does <span class="emphasis"><em>not</em></span>
        take on the current timestamp at insert time except under one of
        the following conditions:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Its default value is defined as
            <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> and no
            value is specified for the column
          </p></li><li class="listitem"><p>
            <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> or any of
            its synonyms such as <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a> is
            explicitly inserted into the column
</p></li></ul>
</div>
<p>
        In other words, a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>
        column defined to permit <code class="literal">NULL</code> values
        auto-initializes only if its definition includes
        <code class="literal">DEFAULT CURRENT_TIMESTAMP</code>:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t (ts TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP);</pre><p>
        If the <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column permits
        <code class="literal">NULL</code> values but its definition does not
        include <code class="literal">DEFAULT CURRENT_TIMESTAMP</code>, you must
        explicitly insert a value corresponding to the current date and
        time. Suppose that tables <code class="literal">t1</code> and
        <code class="literal">t2</code> have these definitions:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (ts TIMESTAMP NULL DEFAULT '0000-00-00 00:00:00');
CREATE TABLE t2 (ts TIMESTAMP NULL DEFAULT NULL);</pre><p>
        To set the <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column in
        either table to the current timestamp at insert time, explicitly
        assign it that value. For example:
      </p><pre data-lang="sql" class="programlisting">INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);
INSERT INTO t1 VALUES (NOW());</pre><p>
        If the
        <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
        system variable is enabled,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> columns permit
        <code class="literal">NULL</code> values only if declared with the
        <code class="literal">NULL</code> attribute. Also,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> columns do not permit
        assigning <code class="literal">NULL</code> to assign the current
        timestamp, whether declared with the <code class="literal">NULL</code> or
        <code class="literal">NOT NULL</code> attribute. To assign the current
        timestamp, set the column to
        <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> or a synonym
        such as <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a>.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="fractional-seconds"></a>11.2.6 Fractional Seconds in Time Values</h3>

</div>

</div>

</div>
<p>
        MySQL has fractional seconds support for
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values, with up to
        microseconds (6 digits) precision:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            To define a column that includes a fractional seconds part,
            use the syntax
            <code class="literal"><em class="replaceable"><code>type_name</code></em>(<em class="replaceable"><code>fsp</code></em>)</code>,
            where <em class="replaceable"><code>type_name</code></em> is
            <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, or
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>, and
            <em class="replaceable"><code>fsp</code></em> is the fractional seconds
            precision. For example:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (t TIME(3), dt DATETIME(6));</pre><p>
            The <em class="replaceable"><code>fsp</code></em> value, if given, must be
            in the range 0 to 6. A value of 0 signifies that there is no
            fractional part. If omitted, the default precision is 0.
            (This differs from the standard SQL default of 6, for
            compatibility with previous MySQL versions.)
          </p></li><li class="listitem"><p>
            Inserting a <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>, or
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> value with a
            fractional seconds part into a column of the same type but
            having fewer fractional digits results in rounding. Consider
            a table created and populated as follows:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE fractest( c1 TIME(2), c2 DATETIME(2), c3 TIMESTAMP(2) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');</pre><p>
            The temporal values are inserted into the table with
            rounding:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT * FROM fractest;</code></strong>
+-------------+------------------------+------------------------+
| c1          | c2                     | c3                     |
+-------------+------------------------+------------------------+
| 17:51:04.78 | 2018-09-08 17:51:04.78 | 2018-09-08 17:51:04.78 |
+-------------+------------------------+------------------------+
</pre><p>
            No warning or error is given when such rounding occurs. This
            behavior follows the SQL standard.
          </p><p>
            To insert the values with truncation instead, enable the
            <a class="link" href="server-administration.html#sqlmode_time_truncate_fractional"><code class="literal">TIME_TRUNCATE_FRACTIONAL</code></a>
            SQL mode:
          </p><pre data-lang="sql" class="programlisting">SET @@sql_mode = sys.list_add(@@sql_mode, 'TIME_TRUNCATE_FRACTIONAL');</pre><p>
            With that SQL mode enabled, the temporal values are inserted
            with truncation:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT * FROM fractest;</code></strong>
+-------------+------------------------+------------------------+
| c1          | c2                     | c3                     |
+-------------+------------------------+------------------------+
| 17:51:04.77 | 2018-09-08 17:51:04.77 | 2018-09-08 17:51:04.77 |
+-------------+------------------------+------------------------+
</pre></li><li class="listitem"><p>
            Functions that take temporal arguments accept values with
            fractional seconds. Return values from temporal functions
            include fractional seconds as appropriate. For example,
            <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a> with no argument
            returns the current date and time with no fractional part,
            but takes an optional argument from 0 to 6 to specify that
            the return value includes a fractional seconds part of that
            many digits.
          </p></li><li class="listitem"><p>
            Syntax for temporal literals produces temporal values:
            <code class="literal">DATE '<em class="replaceable"><code>str</code></em>'</code>,
            <code class="literal">TIME '<em class="replaceable"><code>str</code></em>'</code>,
            and <code class="literal">TIMESTAMP
            '<em class="replaceable"><code>str</code></em>'</code>, and the
            ODBC-syntax equivalents. The resulting value includes a
            trailing fractional seconds part if specified. Previously,
            the temporal type keyword was ignored and these constructs
            produced the string value. See
            <a class="xref" href="language-structure.html#date-and-time-standard-sql-literals" title="Standard SQL and ODBC Date and Time Literals">Standard SQL and ODBC Date and Time Literals</a>
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="date-and-time-type-conversion"></a>11.2.7 Conversion Between Date and Time Types</h3>

</div>

</div>

</div>
<p>
        To some extent, you can convert a value from one temporal type
        to another. However, there may be some alteration of the value
        or loss of information. In all cases, conversion between
        temporal types is subject to the range of valid values for the
        resulting type. For example, although
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values all can be
        specified using the same set of formats, the types do not all
        have the same range of values.
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values cannot be
        earlier than <code class="literal">1970</code> UTC or later than
        <code class="literal">'2038-01-19 03:14:07'</code> UTC. This means that a
        date such as <code class="literal">'1968-01-01'</code>, while valid as a
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> value, is not valid as a
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> value and is converted
        to <code class="literal">0</code>.
      </p><p>
        Conversion of <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> values:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Conversion to a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> or
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> value adds a time
            part of <code class="literal">'00:00:00'</code> because the
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> value contains no time
            information.
          </p></li><li class="listitem"><p>
            Conversion to a <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> value is
            not useful; the result is <code class="literal">'00:00:00'</code>.
</p></li></ul>
</div>
<p>
        Conversion of <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Conversion to a <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> value
            takes fractional seconds into account and rounds the time
            part. For example, <code class="literal">'1999-12-31
            23:59:59.499'</code> becomes
            <code class="literal">'1999-12-31'</code>, whereas
            <code class="literal">'1999-12-31 23:59:59.500'</code> becomes
            <code class="literal">'2000-01-01'</code>.
          </p></li><li class="listitem"><p>
            Conversion to a <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> value
            discards the date part because the
            <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> type contains no date
            information.
</p></li></ul>
</div>
<p>
        For conversion of <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> values to
        other temporal types, the value of
        <a class="link" href="functions.html#function_current-date"><code class="literal">CURRENT_DATE()</code></a> is used for the
        date part. The <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> is
        interpreted as elapsed time (not time of day) and added to the
        date. This means that the date part of the result differs from
        the current date if the time value is outside the range from
        <code class="literal">'00:00:00'</code> to <code class="literal">'23:59:59'</code>.
      </p><p>
        Suppose that the current date is
        <code class="literal">'2012-01-01'</code>.
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> values of
        <code class="literal">'12:00:00'</code>, <code class="literal">'24:00:00'</code>,
        and <code class="literal">'-12:00:00'</code>, when converted to
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> values, result in
        <code class="literal">'2012-01-01 12:00:00'</code>, <code class="literal">'2012-01-02
        00:00:00'</code>, and <code class="literal">'2011-12-31
        12:00:00'</code>, respectively.
      </p><p>
        Conversion of <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> to
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> is similar but discards the
        time part from the result: <code class="literal">'2012-01-01'</code>,
        <code class="literal">'2012-01-02'</code>, and
        <code class="literal">'2011-12-31'</code>, respectively.
      </p><p>
        Explicit conversion can be used to override implicit conversion.
        For example, in comparison of
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> values, the
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> value is coerced to the
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> type by adding a time
        part of <code class="literal">'00:00:00'</code>. To perform the comparison
        by ignoring the time part of the
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> value instead, use the
        <a class="link" href="functions.html#function_cast"><code class="literal">CAST()</code></a> function in the following
        way:
      </p><pre data-lang="sql" class="programlisting"><em class="replaceable"><code>date_col</code></em> = CAST(<em class="replaceable"><code>datetime_col</code></em> AS DATE)
</pre><p>
        Conversion of <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> values to numeric form
        (for example, by adding <code class="literal">+0</code>) depends on
        whether the value contains a fractional seconds part.
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(<em class="replaceable"><code>N</code></em>)</code></a>
        or
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME(<em class="replaceable"><code>N</code></em>)</code></a>
        is converted to integer when <em class="replaceable"><code>N</code></em> is 0
        (or omitted) and to a <code class="literal">DECIMAL</code> value with
        <em class="replaceable"><code>N</code></em> decimal digits when
        <em class="replaceable"><code>N</code></em> is greater than 0:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT CURTIME(), CURTIME()+0, CURTIME(3)+0;</code></strong>
+-----------+-------------+--------------+
| CURTIME() | CURTIME()+0 | CURTIME(3)+0 |
+-----------+-------------+--------------+
| 09:28:00  |       92800 |    92800.887 |
+-----------+-------------+--------------+
mysql&gt; <strong class="userinput"><code>SELECT NOW(), NOW()+0, NOW(3)+0;</code></strong>
+---------------------+----------------+--------------------+
| NOW()               | NOW()+0        | NOW(3)+0           |
+---------------------+----------------+--------------------+
| 2012-08-15 09:28:00 | 20120815092800 | 20120815092800.889 |
+---------------------+----------------+--------------------+
</pre>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="two-digit-years"></a>11.2.8 2-Digit Years in Dates</h3>

</div>

</div>

</div>
<p>
        Date values with 2-digit years are ambiguous because the century
        is unknown. Such values must be interpreted into 4-digit form
        because MySQL stores years internally using 4 digits.
      </p><p>
        For <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> types, MySQL interprets
        dates specified with ambiguous year values using these rules:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Year values in the range <code class="literal">00-69</code> become
            <code class="literal">2000-2069</code>.
          </p></li><li class="listitem"><p>
            Year values in the range <code class="literal">70-99</code> become
            <code class="literal">1970-1999</code>.
</p></li></ul>
</div>
<p>
        For <code class="literal">YEAR</code>, the rules are the same, with this
        exception: A numeric <code class="literal">00</code> inserted into
        <code class="literal">YEAR</code> results in <code class="literal">0000</code>
        rather than <code class="literal">2000</code>. To specify zero for
        <code class="literal">YEAR</code> and have it be interpreted as
        <code class="literal">2000</code>, specify it as a string
        <code class="literal">'0'</code> or <code class="literal">'00'</code>.
      </p><p>
        Remember that these rules are only heuristics that provide
        reasonable guesses as to what your data values mean. If the
        rules used by MySQL do not produce the values you require, you
        must provide unambiguous input containing 4-digit year values.
      </p><p>
        <code class="literal">ORDER BY</code> properly sorts
        <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> values that have 2-digit
        years.
      </p><p>
        Some functions like <a class="link" href="functions.html#function_min"><code class="literal">MIN()</code></a> and
        <a class="link" href="functions.html#function_max"><code class="literal">MAX()</code></a> convert a
        <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> to a number. This means that
        a value with a 2-digit year does not work properly with these
        functions. The fix in this case is to convert the
        <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> to 4-digit year format.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="string-types"></a>11.3 String Data Types</h2>

</div>

</div>

</div>
<div class="toc">
<dl class="toc"><dt><span class="section"><a href="data-types.html#string-type-syntax">11.3.1 String Data Type Syntax</a></span></dt><dt><span class="section"><a href="data-types.html#char">11.3.2 The CHAR and VARCHAR Types</a></span></dt><dt><span class="section"><a href="data-types.html#binary-varbinary">11.3.3 The BINARY and VARBINARY Types</a></span></dt><dt><span class="section"><a href="data-types.html#blob">11.3.4 The BLOB and TEXT Types</a></span></dt><dt><span class="section"><a href="data-types.html#enum">11.3.5 The ENUM Type</a></span></dt><dt><span class="section"><a href="data-types.html#set">11.3.6 The SET Type</a></span></dt></dl>
</div>
<a class="indexterm" name="idm46444337364352"></a><a class="indexterm" name="idm46444337362864"></a><a class="indexterm" name="idm46444337361376"></a><a class="indexterm" name="idm46444337360304"></a><a class="indexterm" name="idm46444337359232"></a><a class="indexterm" name="idm46444337358160"></a><a class="indexterm" name="idm46444337357088"></a><a class="indexterm" name="idm46444337355600"></a><p>
      The string data types are <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
      <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>,
      <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a>,
      <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a>,
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>,
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a>,
      <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>, and
      <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a>.
    </p><p>
      For information about storage requirements of the string data
      types, see <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>.
    </p><p>
      For descriptions of functions that operate on string values, see
      <a class="xref" href="functions.html#string-functions" title="12.7 String Functions and Operators">Section 12.7, “String Functions and Operators”</a>.
</p>
<div class="section">

<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="string-type-syntax"></a>11.3.1 String Data Type Syntax</h3>
</div>
</div>
</div>
<p>
        The string data types are <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>,
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a>,
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a>,
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>,
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a>,
        <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>, and
        <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a>.
      </p><p>
        In some cases, MySQL may change a string column to a type
        different from that given in a <a class="link" href="sql-statements.html#create-table" title="13.1.20 CREATE TABLE Statement"><code class="literal">CREATE
        TABLE</code></a> or <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>
        statement. See <a class="xref" href="sql-statements.html#silent-column-changes" title="13.1.20.7 Silent Column Specification Changes">Section 13.1.20.7, “Silent Column Specification Changes”</a>.
      </p><p>
        For definitions of character string columns
        (<a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, and the
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> types), MySQL interprets
        length specifications in character units. For definitions of
        binary string columns (<a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a>,
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a>, and the
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> types), MySQL interprets
        length specifications in byte units.
      </p><p>
        Column definitions for character string data types
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, the
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> types,
        <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>,
        <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a>, and any synonyms) can
        specify the column character set and collation:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">CHARACTER SET</code> specifies the character
            set. If desired, a collation for the character set can be
            specified with the <code class="literal">COLLATE</code> attribute,
            along with any other attributes. For example:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t
(
    c1 VARCHAR(20) CHARACTER SET utf8,
    c2 TEXT CHARACTER SET latin1 COLLATE latin1_general_cs
);</pre><p>
            This table definition creates a column named
            <code class="literal">c1</code> that has a character set of
            <code class="literal">utf8</code> with the default collation for that
            character set, and a column named <code class="literal">c2</code> that
            has a character set of <code class="literal">latin1</code> and a
            case-sensitive (<code class="literal">_cs</code>) collation.
          </p><p>
            The rules for assigning the character set and collation when
            either or both of <code class="literal">CHARACTER SET</code> and the
            <code class="literal">COLLATE</code> attribute are missing are
            described in <a class="xref" href="charset.html#charset-column" title="10.3.5 Column Character Set and Collation">Section 10.3.5, “Column Character Set and Collation”</a>.
          </p><p>
            <code class="literal">CHARSET</code> is a synonym for
            <code class="literal">CHARACTER SET</code>.
          </p></li><li class="listitem"><p>
            Specifying the <code class="literal">CHARACTER SET binary</code>
            attribute for a character string data type causes the column
            to be created as the corresponding binary string data type:
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> becomes
            <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a>,
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> becomes
            <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a>, and
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> becomes
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>. For the
            <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a> and
            <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> data types, this does not
            occur; they are created as declared. Suppose that you
            specify a table using this definition:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t
(
  c1 VARCHAR(10) CHARACTER SET binary,
  c2 TEXT CHARACTER SET binary,
  c3 ENUM('a','b','c') CHARACTER SET binary
);</pre><p>
            The resulting table has this definition:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t
(
  c1 VARBINARY(10),
  c2 BLOB,
  c3 ENUM('a','b','c') CHARACTER SET binary
);</pre></li><li class="listitem"><p>
            The <code class="literal">BINARY</code> attribute is a nonstandard
            MySQL extension that is shorthand for specifying the binary
            (<code class="literal">_bin</code>) collation of the column character
            set (or of the table default character set if no column
            character set is specified). In this case, comparison and
            sorting are based on numeric character code values. Suppose
            that you specify a table using this definition:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t
(
  c1 VARCHAR(10) CHARACTER SET latin1 BINARY,
  c2 TEXT BINARY
) CHARACTER SET utf8mb4;</pre><p>
            The resulting table has this definition:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t (
  c1 VARCHAR(10) CHARACTER SET latin1 COLLATE latin1_bin,
  c2 TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
) CHARACTER SET utf8mb4;</pre><p>
            In MySQL 8.0, this nonstandard use of the
            <code class="literal">BINARY</code> attribute is ambiguous because the
            <code class="literal">utf8mb4</code> character set has multiple
            <code class="literal">_bin</code> collations. As of MySQL 8.0.17, the
            <code class="literal">BINARY</code> attribute is deprecated and
            support for it will be removed in a future MySQL version.
            Applications should be adjusted to use an explicit
            <code class="literal">_bin</code> collation instead.
          </p><p>
            The use of <code class="literal">BINARY</code> to specify a data type
            or character set remains unchanged.
          </p></li><li class="listitem"><p>
            The <code class="literal">ASCII</code> attribute is shorthand for
            <code class="literal">CHARACTER SET latin1</code>.
          </p></li><li class="listitem"><p>
            The <code class="literal">UNICODE</code> attribute is shorthand for
            <code class="literal">CHARACTER SET ucs2</code>.
</p></li></ul>
</div>
<p>
        Character column comparison and sorting are based on the
        collation assigned to the column. For the
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>,
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a>,
        <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>, and
        <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> data types, you can declare a
        column with a binary (<code class="literal">_bin</code>) collation or the
        <code class="literal">BINARY</code> attribute to cause comparison and
        sorting to use the underlying character code values rather than
        a lexical ordering.
      </p><p>
        For additional information about use of character sets in MySQL,
        see <a class="xref" href="charset.html" title="Chapter 10 Character Sets, Collations, Unicode">Chapter 10, <i>Character Sets, Collations, Unicode</i></a>.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <a class="indexterm" name="idm46444337257536"></a>

            <a class="indexterm" name="idm46444337256464"></a>

            <a class="indexterm" name="idm46444337255392"></a>

            <a class="indexterm" name="idm46444337254320"></a>

            <a class="indexterm" name="idm46444337253248"></a>

            <a class="indexterm" name="idm46444337251760"></a>

            <a class="indexterm" name="idm46444337250272"></a>

            <a class="indexterm" name="idm46444337248784"></a>

            <code class="literal">[NATIONAL] CHAR[(<em class="replaceable"><code>M</code></em>)]
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code>
          </p><p>
            A fixed-length string that is always right-padded with
            spaces to the specified length when stored.
            <em class="replaceable"><code>M</code></em> represents the column length in
            characters. The range of <em class="replaceable"><code>M</code></em> is 0
            to 255. If <em class="replaceable"><code>M</code></em> is omitted, the
            length is 1.
</p><a class="indexterm" name="idm46444337243280"></a>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
              Trailing spaces are removed when
              <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> values are retrieved
              unless the
              <a class="link" href="server-administration.html#sqlmode_pad_char_to_full_length"><code class="literal">PAD_CHAR_TO_FULL_LENGTH</code></a>
              SQL mode is enabled.
</p>
</div>
<p>
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> is shorthand for
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHARACTER</code></a>.
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">NATIONAL CHAR</code></a> (or its
            equivalent short form, <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">NCHAR</code></a>)
            is the standard SQL way to define that a
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> column should use some
            predefined character set. MySQL uses <code class="literal">utf8</code>
            as this predefined character set.
            <a class="xref" href="charset.html#charset-national" title="10.3.7 The National Character Set">Section 10.3.7, “The National Character Set”</a>.
          </p><p>
            The <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">CHAR BYTE</code></a> data type is an
            alias for the <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a> data
            type. This is a compatibility feature.
          </p><p>
            MySQL permits you to create a column of type
            <code class="literal">CHAR(0)</code>. This is useful primarily when
            you must be compliant with old applications that depend on
            the existence of a column but that do not actually use its
            value. <code class="literal">CHAR(0)</code> is also quite nice when
            you need a column that can take only two values: A column
            that is defined as <code class="literal">CHAR(0) NULL</code> occupies
            only one bit and can take only the values
            <code class="literal">NULL</code> and <code class="literal">''</code> (the empty
            string).
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337217040"></a>

            <a class="indexterm" name="idm46444337215968"></a>

            <a class="indexterm" name="idm46444337214880"></a>

            <a class="indexterm" name="idm46444337213808"></a>

            <a class="indexterm" name="idm46444337212736"></a>

            <a class="indexterm" name="idm46444337211648"></a>

            <a class="indexterm" name="idm46444337210576"></a>

            <a class="indexterm" name="idm46444337209088"></a>

            <a class="indexterm" name="idm46444337207600"></a>

            <a class="indexterm" name="idm46444337206112"></a>

            <a class="indexterm" name="idm46444337204624"></a>

            <a class="indexterm" name="idm46444337203136"></a>

            <code class="literal">[NATIONAL] VARCHAR(<em class="replaceable"><code>M</code></em>)
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code>
          </p><a class="indexterm" name="idm46444337199520"></a><p>
            A variable-length string. <em class="replaceable"><code>M</code></em>
            represents the maximum column length in characters. The
            range of <em class="replaceable"><code>M</code></em> is 0 to 65,535. The
            effective maximum length of a
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> is subject to the
            maximum row size (65,535 bytes, which is shared among all
            columns) and the character set used. For example,
            <code class="literal">utf8</code> characters can require up to three
            bytes per character, so a
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column that uses the
            <code class="literal">utf8</code> character set can be declared to be
            a maximum of 21,844 characters. See
            <a class="xref" href="optimization.html#column-count-limit" title="8.4.7 Limits on Table Column Count and Row Size">Section 8.4.7, “Limits on Table Column Count and Row Size”</a>.
          </p><p>
            MySQL stores <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> values
            as a 1-byte or 2-byte length prefix plus data. The length
            prefix indicates the number of bytes in the value. A
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column uses one
            length byte if values require no more than 255 bytes, two
            length bytes if values may require more than 255 bytes.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
              MySQL follows the standard SQL specification, and does
              <span class="emphasis"><em>not</em></span> remove trailing spaces from
              <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> values.
</p>
</div>
<p>
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> is shorthand for
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHARACTER VARYING</code></a>.
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">NATIONAL VARCHAR</code></a> is the
            standard SQL way to define that a
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column should use
            some predefined character set. MySQL uses
            <code class="literal">utf8</code> as this predefined character set.
            <a class="xref" href="charset.html#charset-national" title="10.3.7 The National Character Set">Section 10.3.7, “The National Character Set”</a>.
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">NVARCHAR</code></a> is shorthand for
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">NATIONAL VARCHAR</code></a>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337174048"></a>

            <a class="indexterm" name="idm46444337172976"></a>

            <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY[(<em class="replaceable"><code>M</code></em>)]</code></a>
          </p><p>
            The <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">BINARY</code></a> type is similar to
            the <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> type, but stores
            binary byte strings rather than nonbinary character strings.
            An optional length <em class="replaceable"><code>M</code></em> represents
            the column length in bytes. If omitted,
            <em class="replaceable"><code>M</code></em> defaults to 1.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337163360"></a>

            <a class="indexterm" name="idm46444337162288"></a>

            <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY(<em class="replaceable"><code>M</code></em>)</code></a>
          </p><p>
            The <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a> type is similar
            to the <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> type, but
            stores binary byte strings rather than nonbinary character
            strings. <em class="replaceable"><code>M</code></em> represents the maximum
            column length in bytes.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337153152"></a>

            <a class="indexterm" name="idm46444337152080"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYBLOB</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> column with a maximum
            length of 255 (2<sup>8</sup> − 1)
            bytes. Each <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYBLOB</code></a> value is
            stored using a 1-byte length prefix that indicates the
            number of bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337143280"></a>

            <a class="indexterm" name="idm46444337142208"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYTEXT
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> column with a maximum
            length of 255 (2<sup>8</sup> − 1)
            characters. The effective maximum length is less if the
            value contains multibyte characters. Each
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYTEXT</code></a> value is stored
            using a 1-byte length prefix that indicates the number of
            bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337132288"></a>

            <a class="indexterm" name="idm46444337131216"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB[(<em class="replaceable"><code>M</code></em>)]</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> column with a maximum
            length of 65,535 (2<sup>16</sup> − 1)
            bytes. Each <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> value is
            stored using a 2-byte length prefix that indicates the
            number of bytes in the value.
          </p><p>
            An optional length <em class="replaceable"><code>M</code></em> can be given
            for this type. If this is done, MySQL creates the column as
            the smallest <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> type large
            enough to hold values <em class="replaceable"><code>M</code></em> bytes
            long.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337119392"></a>

            <a class="indexterm" name="idm46444337118320"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT[(<em class="replaceable"><code>M</code></em>)]
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> column with a maximum
            length of 65,535 (2<sup>16</sup> − 1)
            characters. The effective maximum length is less if the
            value contains multibyte characters. Each
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> value is stored using a
            2-byte length prefix that indicates the number of bytes in
            the value.
          </p><p>
            An optional length <em class="replaceable"><code>M</code></em> can be given
            for this type. If this is done, MySQL creates the column as
            the smallest <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> type large
            enough to hold values <em class="replaceable"><code>M</code></em>
            characters long.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337105328"></a>

            <a class="indexterm" name="idm46444337104256"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMBLOB</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> column with a maximum
            length of 16,777,215 (2<sup>24</sup> −
            1) bytes. Each <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMBLOB</code></a>
            value is stored using a 3-byte length prefix that indicates
            the number of bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337095392"></a>

            <a class="indexterm" name="idm46444337094320"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> column with a maximum
            length of 16,777,215 (2<sup>24</sup> −
            1) characters. The effective maximum length is less if the
            value contains multibyte characters. Each
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT</code></a> value is stored
            using a 3-byte length prefix that indicates the number of
            bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337083680"></a>

            <a class="indexterm" name="idm46444337082608"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGBLOB</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> column with a maximum
            length of 4,294,967,295 or 4GB
            (2<sup>32</sup> − 1) bytes. The
            effective maximum length of
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGBLOB</code></a> columns depends on
            the configured maximum packet size in the client/server
            protocol and available memory. Each
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGBLOB</code></a> value is stored
            using a 4-byte length prefix that indicates the number of
            bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337072336"></a>

            <a class="indexterm" name="idm46444337071264"></a>

            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGTEXT
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            A <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> column with a maximum
            length of 4,294,967,295 or 4GB
            (2<sup>32</sup> − 1) characters. The
            effective maximum length is less if the value contains
            multibyte characters. The effective maximum length of
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGTEXT</code></a>
            columns also depends on the configured maximum packet size
            in the client/server protocol and available memory. Each
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGTEXT</code></a>
            value is stored using a 4-byte length prefix that indicates
            the number of bytes in the value.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337059888"></a>

            <a class="indexterm" name="idm46444337058816"></a>

            <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM('<em class="replaceable"><code>value1</code></em>','<em class="replaceable"><code>value2</code></em>',...)
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            An enumeration. A string object that can have only one
            value, chosen from the list of values
            <code class="literal">'<em class="replaceable"><code>value1</code></em>'</code>,
            <code class="literal">'<em class="replaceable"><code>value2</code></em>'</code>,
            <code class="literal">...</code>, <code class="literal">NULL</code> or the
            special <code class="literal">''</code> error value.
            <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a> values are represented
            internally as integers.
          </p><p>
            An <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a> column can have a
            maximum of 65,535 distinct elements.
          </p><p>
            The maximum supported length of an individual
            <code class="literal">ENUM</code> element is
            <em class="replaceable"><code>M</code></em> &lt;= 255 and
            (<em class="replaceable"><code>M</code></em> x
            <em class="replaceable"><code>w</code></em>) &lt;= 1020, where
            <code class="literal">M</code> is the element literal length and
            <em class="replaceable"><code>w</code></em> is the number of bytes required
            for the maximum-length character in the character set.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444337040096"></a>

            <a class="indexterm" name="idm46444337039024"></a>

            <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET('<em class="replaceable"><code>value1</code></em>','<em class="replaceable"><code>value2</code></em>',...)
            [CHARACTER SET <em class="replaceable"><code>charset_name</code></em>]
            [COLLATE
            <em class="replaceable"><code>collation_name</code></em>]</code></a>
          </p><p>
            A set. A string object that can have zero or more values,
            each of which must be chosen from the list of values
            <code class="literal">'<em class="replaceable"><code>value1</code></em>'</code>,
            <code class="literal">'<em class="replaceable"><code>value2</code></em>'</code>,
            <code class="literal">...</code> <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a>
            values are represented internally as integers.
          </p><p>
            A <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> column can have a
            maximum of 64 distinct members.
          </p><p>
            The maximum supported length of an individual
            <code class="literal">SET</code> element is
            <em class="replaceable"><code>M</code></em> &lt;= 255 and
            (<em class="replaceable"><code>M</code></em> x
            <em class="replaceable"><code>w</code></em>) &lt;= 1020, where
            <code class="literal">M</code> is the element literal length and
            <em class="replaceable"><code>w</code></em> is the number of bytes required
            for the maximum-length character in the character set.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="char"></a>11.3.2 The CHAR and VARCHAR Types</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444337022432"></a><a class="indexterm" name="idm46444337020976"></a><a class="indexterm" name="idm46444337019488"></a><p>
        The <code class="literal">CHAR</code> and <code class="literal">VARCHAR</code> types
        are similar, but differ in the way they are stored and
        retrieved. They also differ in maximum length and in whether
        trailing spaces are retained.
      </p><p>
        The <code class="literal">CHAR</code> and <code class="literal">VARCHAR</code> types
        are declared with a length that indicates the maximum number of
        characters you want to store. For example,
        <code class="literal">CHAR(30)</code> can hold up to 30 characters.
      </p><p>
        The length of a <code class="literal">CHAR</code> column is fixed to the
        length that you declare when you create the table. The length
        can be any value from 0 to 255. When <code class="literal">CHAR</code>
        values are stored, they are right-padded with spaces to the
        specified length. When <code class="literal">CHAR</code> values are
        retrieved, trailing spaces are removed unless the
        <a class="link" href="server-administration.html#sqlmode_pad_char_to_full_length"><code class="literal">PAD_CHAR_TO_FULL_LENGTH</code></a> SQL
        mode is enabled.
      </p><p>
        Values in <code class="literal">VARCHAR</code> columns are variable-length
        strings. The length can be specified as a value from 0 to
        65,535. The effective maximum length of a
        <code class="literal">VARCHAR</code> is subject to the maximum row size
        (65,535 bytes, which is shared among all columns) and the
        character set used. See <a class="xref" href="optimization.html#column-count-limit" title="8.4.7 Limits on Table Column Count and Row Size">Section 8.4.7, “Limits on Table Column Count and Row Size”</a>.
      </p><p>
        In contrast to <code class="literal">CHAR</code>,
        <code class="literal">VARCHAR</code> values are stored as a 1-byte or
        2-byte length prefix plus data. The length prefix indicates the
        number of bytes in the value. A column uses one length byte if
        values require no more than 255 bytes, two length bytes if
        values may require more than 255 bytes.
      </p><p>
        If strict SQL mode is not enabled and you assign a value to a
        <code class="literal">CHAR</code> or <code class="literal">VARCHAR</code> column
        that exceeds the column's maximum length, the value is truncated
        to fit and a warning is generated. For truncation of nonspace
        characters, you can cause an error to occur (rather than a
        warning) and suppress insertion of the value by using strict SQL
        mode. See <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><p>
        For <code class="literal">VARCHAR</code> columns, trailing spaces in
        excess of the column length are truncated prior to insertion and
        a warning is generated, regardless of the SQL mode in use. For
        <code class="literal">CHAR</code> columns, truncation of excess trailing
        spaces from inserted values is performed silently regardless of
        the SQL mode.
      </p><p>
        <code class="literal">VARCHAR</code> values are not padded when they are
        stored. Trailing spaces are retained when values are stored and
        retrieved, in conformance with standard SQL.
      </p><p>
        The following table illustrates the differences between
        <code class="literal">CHAR</code> and <code class="literal">VARCHAR</code> by
        showing the result of storing various string values into
        <code class="literal">CHAR(4)</code> and <code class="literal">VARCHAR(4)</code>
        columns (assuming that the column uses a single-byte character
        set such as <code class="literal">latin1</code>).
</p>
<div class="informaltable">
<table summary="Illustration of the difference between CHAR and VARCHAR storage requirements by showing the required storage for various string values in CHAR(4) and VARCHAR(4) columns."><col width="15%"><col width="15%"><col width="20%"><col width="15%"><col width="20%"><thead><tr>
            <th scope="col">Value</th>
            <th scope="col"><code class="literal">CHAR(4)</code></th>
            <th scope="col">Storage Required</th>
            <th scope="col"><code class="literal">VARCHAR(4)</code></th>
            <th scope="col">Storage Required</th>
          </tr></thead><tbody><tr>
            <td scope="row"><code class="literal">''</code></td>
            <td><code class="literal">'    '</code></td>
            <td>4 bytes</td>
            <td><code class="literal">''</code></td>
            <td>1 byte</td>
          </tr><tr>
            <td scope="row"><code class="literal">'ab'</code></td>
            <td><code class="literal">'ab  '</code></td>
            <td>4 bytes</td>
            <td><code class="literal">'ab'</code></td>
            <td>3 bytes</td>
          </tr><tr>
            <td scope="row"><code class="literal">'abcd'</code></td>
            <td><code class="literal">'abcd'</code></td>
            <td>4 bytes</td>
            <td><code class="literal">'abcd'</code></td>
            <td>5 bytes</td>
          </tr><tr>
            <td scope="row"><code class="literal">'abcdefgh'</code></td>
            <td><code class="literal">'abcd'</code></td>
            <td>4 bytes</td>
            <td><code class="literal">'abcd'</code></td>
            <td>5 bytes</td>
</tr></tbody></table>
</div>
<p>
        The values shown as stored in the last row of the table apply
        <span class="emphasis"><em>only when not using strict mode</em></span>; if MySQL
        is running in strict mode, values that exceed the column length
        are <span class="emphasis"><em>not stored</em></span>, and an error results.
      </p><p>
        <code class="literal">InnoDB</code> encodes fixed-length fields greater
        than or equal to 768 bytes in length as variable-length fields,
        which can be stored off-page. For example, a
        <code class="literal">CHAR(255)</code> column can exceed 768 bytes if the
        maximum byte length of the character set is greater than 3, as
        it is with <code class="literal">utf8mb4</code>.
      </p><p>
        If a given value is stored into the <code class="literal">CHAR(4)</code>
        and <code class="literal">VARCHAR(4)</code> columns, the values retrieved
        from the columns are not always the same because trailing spaces
        are removed from <code class="literal">CHAR</code> columns upon retrieval.
        The following example illustrates this difference:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE vc (v VARCHAR(4), c CHAR(4));</code></strong>
Query OK, 0 rows affected (0.01 sec)

mysql&gt; <strong class="userinput"><code>INSERT INTO vc VALUES ('ab  ', 'ab  ');</code></strong>
Query OK, 1 row affected (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT CONCAT('(', v, ')'), CONCAT('(', c, ')') FROM vc;</code></strong>
+---------------------+---------------------+
| CONCAT('(', v, ')') | CONCAT('(', c, ')') |
+---------------------+---------------------+
| (ab  )              | (ab)                |
+---------------------+---------------------+
1 row in set (0.06 sec)
</pre><p>
        Values in <code class="literal">CHAR</code> and <code class="literal">VARCHAR</code>
        columns are sorted and compared according to the character set
        collation assigned to the column.
      </p><a class="indexterm" name="idm46444336942944"></a><a class="indexterm" name="idm46444336941456"></a><a class="indexterm" name="idm46444336940384"></a><a class="indexterm" name="idm46444336938896"></a><p>
        Most MySQL collations have a pad attribute of PAD SPACE. The
        exceptions are Unicode collations based on UCA 9.0.0 and higher,
        which have a pad attribute of NO PAD. (see
        <a class="xref" href="charset.html#charset-unicode-sets" title="10.10.1 Unicode Character Sets">Section 10.10.1, “Unicode Character Sets”</a>).
      </p><p>
        To determine the pad attribute for a collation, use the
        <code class="literal">INFORMATION_SCHEMA</code>
        <a class="link" href="information-schema.html#collations-table" title="25.6 The INFORMATION_SCHEMA COLLATIONS Table"><code class="literal">COLLATIONS</code></a> table, which has a
        <code class="literal">PAD_ATTRIBUTE</code> column.
      </p><p>
        The pad attribute determines how trailing spaces are treated for
        comparison of nonbinary strings (<code class="literal">CHAR</code>,
        <code class="literal">VARCHAR</code>, and <code class="literal">TEXT</code> values).
        NO PAD collations treat spaces at the end of strings like any
        other character. For PAD SPACE collations, trailing spaces are
        insignificant in comparisons; strings are compared without
        regard to any trailing spaces. <span class="quote">“<span class="quote">Comparison</span>”</span> in this
        context does not include the <a class="link" href="functions.html#operator_like"><code class="literal">LIKE</code></a>
        pattern-matching operator, for which trailing spaces are
        significant. For example:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE names (myname CHAR(10));</code></strong>
Query OK, 0 rows affected (0.03 sec)

mysql&gt; <strong class="userinput"><code>INSERT INTO names VALUES ('Jones');</code></strong>
Query OK, 1 row affected (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT myname = 'Jones', myname = 'Jones  ' FROM names;</code></strong>
+--------------------+--------------------+
| myname = 'Jones'   | myname = 'Jones  ' |
+--------------------+--------------------+
|                  1 |                  1 |
+--------------------+--------------------+
1 row in set (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT myname LIKE 'Jones', myname LIKE 'Jones  ' FROM names;</code></strong>
+-----------------------+-----------------------+
| myname LIKE 'Jones'   | myname LIKE 'Jones  ' |
+-----------------------+-----------------------+
|                     1 |                     0 |
+-----------------------+-----------------------+
1 row in set (0.00 sec)
</pre><p>
        This is true for all MySQL versions, and is not affected by the
        server SQL mode.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          For more information about MySQL character sets and
          collations, see <a class="xref" href="charset.html" title="Chapter 10 Character Sets, Collations, Unicode">Chapter 10, <i>Character Sets, Collations, Unicode</i></a>. For additional
          information about storage requirements, see
          <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>.
</p>
</div>
<p>
        For those cases where trailing pad characters are stripped or
        comparisons ignore them, if a column has an index that requires
        unique values, inserting into the column values that differ only
        in number of trailing pad characters will result in a
        duplicate-key error. For example, if a table contains
        <code class="literal">'a'</code>, an attempt to store
        <code class="literal">'a '</code> causes a duplicate-key error.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="binary-varbinary"></a>11.3.3 The BINARY and VARBINARY Types</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336917600"></a><a class="indexterm" name="idm46444336916560"></a><a class="indexterm" name="idm46444336915488"></a><a class="indexterm" name="idm46444336914000"></a><p>
        The <code class="literal">BINARY</code> and <code class="literal">VARBINARY</code>
        types are similar to <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> and
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, except that they store
        binary strings rather than nonbinary strings. That is, they
        store byte strings rather than character strings. This means
        they have the <code class="literal">binary</code> character set and
        collation, and comparison and sorting are based on the numeric
        values of the bytes in the values.
      </p><p>
        The permissible maximum length is the same for
        <code class="literal">BINARY</code> and <code class="literal">VARBINARY</code> as it
        is for <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> and
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, except that the length
        for <code class="literal">BINARY</code> and <code class="literal">VARBINARY</code>
        is measured in bytes rather than characters.
      </p><p>
        The <code class="literal">BINARY</code> and <code class="literal">VARBINARY</code>
        data types are distinct from the <code class="literal">CHAR BINARY</code>
        and <code class="literal">VARCHAR BINARY</code> data types. For the latter
        types, the <code class="literal">BINARY</code> attribute does not cause
        the column to be treated as a binary string column. Instead, it
        causes the binary (<code class="literal">_bin</code>) collation for the
        column character set (or the table default character set if no
        column character set is specified) to be used, and the column
        itself stores nonbinary character strings rather than binary
        byte strings. For example, if the default character set is
        <code class="literal">utf8mb4</code>, <code class="literal">CHAR(5) BINARY</code> is
        treated as <code class="literal">CHAR(5) CHARACTER SET utf8mb4 COLLATE
        utf8mb4_bin</code>. This differs from
        <code class="literal">BINARY(5)</code>, which stores 5-byte binary strings
        that have the <code class="literal">binary</code> character set and
        collation. For information about the differences between the
        <code class="literal">binary</code> collation of the
        <code class="literal">binary</code> character set and the
        <code class="literal">_bin</code> collations of nonbinary character sets,
        see <a class="xref" href="charset.html#charset-binary-collations" title="10.8.5 The binary Collation Compared to _bin Collations">Section 10.8.5, “The binary Collation Compared to _bin Collations”</a>.
      </p><p>
        If strict SQL mode is not enabled and you assign a value to a
        <code class="literal">BINARY</code> or <code class="literal">VARBINARY</code> column
        that exceeds the column's maximum length, the value is truncated
        to fit and a warning is generated. For cases of truncation, to
        cause an error to occur (rather than a warning) and suppress
        insertion of the value, use strict SQL mode. See
        <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><p>
        When <code class="literal">BINARY</code> values are stored, they are
        right-padded with the pad value to the specified length. The pad
        value is <code class="literal">0x00</code> (the zero byte). Values are
        right-padded with <code class="literal">0x00</code> for inserts, and no
        trailing bytes are removed for retrievals. All bytes are
        significant in comparisons, including <code class="literal">ORDER
        BY</code> and <code class="literal">DISTINCT</code> operations.
        <code class="literal">0x00</code> and space differ in comparisons, with
        <code class="literal">0x00</code> sorting before space.
      </p><p>
        Example: For a <code class="literal">BINARY(3)</code> column,
        <code class="literal">'a '</code> becomes
        <code class="literal">'a \0'</code> when inserted.
        <code class="literal">'a\0'</code> becomes <code class="literal">'a\0\0'</code> when
        inserted. Both inserted values remain unchanged for retrievals.
      </p><p>
        For <code class="literal">VARBINARY</code>, there is no padding for
        inserts and no bytes are stripped for retrievals. All bytes are
        significant in comparisons, including <code class="literal">ORDER
        BY</code> and <code class="literal">DISTINCT</code> operations.
        <code class="literal">0x00</code> and space differ in comparisons, with
        <code class="literal">0x00</code> sorting before space.
      </p><p>
        For those cases where trailing pad bytes are stripped or
        comparisons ignore them, if a column has an index that requires
        unique values, inserting values into the column that differ only
        in number of trailing pad bytes results in a duplicate-key
        error. For example, if a table contains <code class="literal">'a'</code>,
        an attempt to store <code class="literal">'a\0'</code> causes a
        duplicate-key error.
      </p><p>
        You should consider the preceding padding and stripping
        characteristics carefully if you plan to use the
        <code class="literal">BINARY</code> data type for storing binary data and
        you require that the value retrieved be exactly the same as the
        value stored. The following example illustrates how
        <code class="literal">0x00</code>-padding of <code class="literal">BINARY</code>
        values affects column value comparisons:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t (c BINARY(3));</code></strong>
Query OK, 0 rows affected (0.01 sec)

mysql&gt; <strong class="userinput"><code>INSERT INTO t SET c = 'a';</code></strong>
Query OK, 1 row affected (0.01 sec)

mysql&gt; <strong class="userinput"><code>SELECT HEX(c), c = 'a', c = 'a\0\0' from t;</code></strong>
+--------+---------+-------------+
| HEX(c) | c = 'a' | c = 'a\0\0' |
+--------+---------+-------------+
| 610000 |       0 |           1 |
+--------+---------+-------------+
1 row in set (0.09 sec)
</pre><p>
        If the value retrieved must be the same as the value specified
        for storage with no padding, it might be preferable to use
        <code class="literal">VARBINARY</code> or one of the
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> data types instead.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="blob"></a>11.3.4 The BLOB and TEXT Types</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336858832"></a><a class="indexterm" name="idm46444336857760"></a><a class="indexterm" name="idm46444336856688"></a><a class="indexterm" name="idm46444336855200"></a><a class="indexterm" name="idm46444336853712"></a><a class="indexterm" name="idm46444336852640"></a><p>
        A <code class="literal">BLOB</code> is a binary large object that can hold
        a variable amount of data. The four <code class="literal">BLOB</code>
        types are <code class="literal">TINYBLOB</code>, <code class="literal">BLOB</code>,
        <code class="literal">MEDIUMBLOB</code>, and <code class="literal">LONGBLOB</code>.
        These differ only in the maximum length of the values they can
        hold. The four <code class="literal">TEXT</code> types are
        <code class="literal">TINYTEXT</code>, <code class="literal">TEXT</code>,
        <code class="literal">MEDIUMTEXT</code>, and <code class="literal">LONGTEXT</code>.
        These correspond to the four <code class="literal">BLOB</code> types and
        have the same maximum lengths and storage requirements. See
        <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>.
      </p><p>
        <code class="literal">BLOB</code> values are treated as binary strings
        (byte strings). They have the <code class="literal">binary</code>
        character set and collation, and comparison and sorting are
        based on the numeric values of the bytes in column values.
        <code class="literal">TEXT</code> values are treated as nonbinary strings
        (character strings). They have a character set other than
        <code class="literal">binary</code>, and values are sorted and compared
        based on the collation of the character set.
      </p><p>
        If strict SQL mode is not enabled and you assign a value to a
        <code class="literal">BLOB</code> or <code class="literal">TEXT</code> column that
        exceeds the column's maximum length, the value is truncated to
        fit and a warning is generated. For truncation of nonspace
        characters, you can cause an error to occur (rather than a
        warning) and suppress insertion of the value by using strict SQL
        mode. See <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><p>
        Truncation of excess trailing spaces from values to be inserted
        into <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> columns always
        generates a warning, regardless of the SQL mode.
      </p><p>
        For <code class="literal">TEXT</code> and <code class="literal">BLOB</code> columns,
        there is no padding on insert and no bytes are stripped on
        select.
      </p><p>
        If a <code class="literal">TEXT</code> column is indexed, index entry
        comparisons are space-padded at the end. This means that, if the
        index requires unique values, duplicate-key errors will occur
        for values that differ only in the number of trailing spaces.
        For example, if a table contains <code class="literal">'a'</code>, an
        attempt to store <code class="literal">'a '</code> causes a
        duplicate-key error. This is not true for
        <code class="literal">BLOB</code> columns.
      </p><p>
        In most respects, you can regard a <code class="literal">BLOB</code>
        column as a <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a> column that
        can be as large as you like. Similarly, you can regard a
        <code class="literal">TEXT</code> column as a
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column.
        <code class="literal">BLOB</code> and <code class="literal">TEXT</code> differ from
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a> and
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> in the following ways:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            For indexes on <code class="literal">BLOB</code> and
            <code class="literal">TEXT</code> columns, you must specify an index
            prefix length. For <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a> and
            <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, a prefix length is
            optional. See <a class="xref" href="optimization.html#column-indexes" title="8.3.5 Column Indexes">Section 8.3.5, “Column Indexes”</a>.
          </p></li><li class="listitem"><p>
            <a class="indexterm" name="idm46444336812336"></a>

            <a class="indexterm" name="idm46444336810848"></a>

            <a class="indexterm" name="idm46444336809360"></a>

            <code class="literal">BLOB</code> and <code class="literal">TEXT</code> columns
            cannot have <code class="literal">DEFAULT</code> values.
</p></li></ul>
</div>
<p>
        If you use the <code class="literal">BINARY</code> attribute with a
        <code class="literal">TEXT</code> data type, the column is assigned the
        binary (<code class="literal">_bin</code>) collation of the column
        character set.
      </p><p>
        <code class="literal">LONG</code> and <code class="literal">LONG VARCHAR</code> map
        to the <code class="literal">MEDIUMTEXT</code> data type. This is a
        compatibility feature.
      </p><p>
        MySQL Connector/ODBC defines <code class="literal">BLOB</code> values as
        <code class="literal">LONGVARBINARY</code> and <code class="literal">TEXT</code>
        values as <code class="literal">LONGVARCHAR</code>.
      </p><p>
        Because <code class="literal">BLOB</code> and <code class="literal">TEXT</code>
        values can be extremely long, you might encounter some
        constraints in using them:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Only the first
            <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a> bytes of
            the column are used when sorting. The default value of
            <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a> is 1024.
            You can make more bytes significant in sorting or grouping
            by increasing the value of
            <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a> at server
            startup or runtime. Any client can change the value of its
            session <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a>
            variable:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET max_sort_length = 2000;</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT id, comment FROM t</code></strong>
    -&gt; <strong class="userinput"><code>ORDER BY comment;</code></strong>
</pre></li><li class="listitem"><p>
            Instances of <code class="literal">BLOB</code> or
            <code class="literal">TEXT</code> columns in the result of a query
            that is processed using a temporary table causes the server
            to use a table on disk rather than in memory because the
            <code class="literal">MEMORY</code> storage engine does not support
            those data types (see
            <a class="xref" href="optimization.html#internal-temporary-tables" title="8.4.4 Internal Temporary Table Use in MySQL">Section 8.4.4, “Internal Temporary Table Use in MySQL”</a>). Use of disk
            incurs a performance penalty, so include
            <code class="literal">BLOB</code> or <code class="literal">TEXT</code> columns
            in the query result only if they are really needed. For
            example, avoid using
            <a class="link" href="sql-statements.html#select" title="13.2.10 SELECT Statement"><code class="literal">SELECT *</code></a>,
            which selects all columns.
          </p></li><li class="listitem"><p>
            The maximum size of a <code class="literal">BLOB</code> or
            <code class="literal">TEXT</code> object is determined by its type,
            but the largest value you actually can transmit between the
            client and server is determined by the amount of available
            memory and the size of the communications buffers. You can
            change the message buffer size by changing the value of the
            <a class="link" href="server-administration.html#sysvar_max_allowed_packet"><code class="literal">max_allowed_packet</code></a>
            variable, but you must do so for both the server and your
            client program. For example, both <a class="link" href="programs.html#mysql" title="4.5.1 mysql — The MySQL Command-Line Client"><span class="command"><strong>mysql</strong></span></a>
            and <a class="link" href="programs.html#mysqldump" title="4.5.4 mysqldump — A Database Backup Program"><span class="command"><strong>mysqldump</strong></span></a> enable you to change the
            client-side
            <a class="link" href="server-administration.html#sysvar_max_allowed_packet"><code class="literal">max_allowed_packet</code></a> value.
            See <a class="xref" href="server-administration.html#server-configuration" title="5.1.1 Configuring the Server">Section 5.1.1, “Configuring the Server”</a>,
            <a class="xref" href="programs.html#mysql" title="4.5.1 mysql — The MySQL Command-Line Client">Section 4.5.1, “<span class="command"><strong>mysql</strong></span> — The MySQL Command-Line Client”</a>, and <a class="xref" href="programs.html#mysqldump" title="4.5.4 mysqldump — A Database Backup Program">Section 4.5.4, “<span class="command"><strong>mysqldump</strong></span> — A Database Backup Program”</a>.
            You may also want to compare the packet sizes and the size
            of the data objects you are storing with the storage
            requirements, see <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>
</p></li></ul>
</div>
<p>
        Each <code class="literal">BLOB</code> or <code class="literal">TEXT</code> value is
        represented internally by a separately allocated object. This is
        in contrast to all other data types, for which storage is
        allocated once per column when the table is opened.
      </p><p>
        In some cases, it may be desirable to store binary data such as
        media files in <code class="literal">BLOB</code> or
        <code class="literal">TEXT</code> columns. You may find MySQL's string
        handling functions useful for working with such data. See
        <a class="xref" href="functions.html#string-functions" title="12.7 String Functions and Operators">Section 12.7, “String Functions and Operators”</a>. For security and other
        reasons, it is usually preferable to do so using application
        code rather than giving application users the
        <a class="link" href="security.html#priv_file"><code class="literal">FILE</code></a> privilege. You can discuss
        specifics for various languages and platforms in the MySQL
        Forums (<a class="ulink" href="http://forums.mysql.com/" target="_top">http://forums.mysql.com/</a>).
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="enum"></a>11.3.5 The ENUM Type</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336759888"></a><a class="indexterm" name="idm46444336758816"></a><p>
        An <code class="literal">ENUM</code> is a string object with a value
        chosen from a list of permitted values that are enumerated
        explicitly in the column specification at table creation time.
        It has these advantages:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Compact data storage in situations where a column has a
            limited set of possible values. The strings you specify as
            input values are automatically encoded as numbers. See
            <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a> for the storage
            requirements for <code class="literal">ENUM</code> types.
          </p></li><li class="listitem"><p>
            Readable queries and output. The numbers are translated back
            to the corresponding strings in query results.
</p></li></ul>
</div>
<p>
        and these potential issues to consider:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            If you make enumeration values that look like numbers, it is
            easy to mix up the literal values with their internal index
            numbers, as explained in <a class="xref" href="data-types.html#enum-limits" title="Enumeration Limitations">Enumeration Limitations</a>.
          </p></li><li class="listitem"><p>
            Using <code class="literal">ENUM</code> columns in <code class="literal">ORDER
            BY</code> clauses requires extra care, as explained in
            <a class="xref" href="data-types.html#enum-sorting" title="Enumeration Sorting">Enumeration Sorting</a>.
</p></li></ul>
</div>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><a class="xref" href="data-types.html#enum-using" title="Creating and Using ENUM Columns">Creating and Using ENUM Columns</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#enum-indexes" title="Index Values for Enumeration Literals">Index Values for Enumeration Literals</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#enum-literals" title="Handling of Enumeration Literals">Handling of Enumeration Literals</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#enum-nulls" title="Empty or NULL Enumeration Values">Empty or NULL Enumeration Values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#enum-sorting" title="Enumeration Sorting">Enumeration Sorting</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#enum-limits" title="Enumeration Limitations">Enumeration Limitations</a></p></li></ul>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-using"></a>Creating and Using ENUM Columns</h4>

</div>

</div>

</div>
<p>
          An enumeration value must be a quoted string literal. For
          example, you can create a table with an
          <code class="literal">ENUM</code> column like this:
        </p><pre data-lang="sql" class="programlisting">CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
  ('polo shirt','small');
SELECT name, size FROM shirts WHERE size = 'medium';
+---------+--------+
| name    | size   |
+---------+--------+
| t-shirt | medium |
+---------+--------+
UPDATE shirts SET size = 'small' WHERE size = 'large';
COMMIT;</pre><p>
          Inserting 1 million rows into this table with a value of
          <code class="literal">'medium'</code> would require 1 million bytes of
          storage, as opposed to 6 million bytes if you stored the
          actual string <code class="literal">'medium'</code> in a
          <code class="literal">VARCHAR</code> column.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-indexes"></a>Index Values for Enumeration Literals</h4>

</div>

</div>

</div>
<p>
          Each enumeration value has an index:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              The elements listed in the column specification are
              assigned index numbers, beginning with 1.
            </p></li><li class="listitem"><p>
              The index value of the empty string error value is 0. This
              means that you can use the following
              <a class="link" href="sql-statements.html#select" title="13.2.10 SELECT Statement"><code class="literal">SELECT</code></a> statement to find
              rows into which invalid <code class="literal">ENUM</code> values
              were assigned:
            </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT * FROM <em class="replaceable"><code>tbl_name</code></em> WHERE <em class="replaceable"><code>enum_col</code></em>=0;</code></strong>
</pre></li><li class="listitem"><p>
              The index of the <code class="literal">NULL</code> value is
              <code class="literal">NULL</code>.
            </p></li><li class="listitem"><p>
              The term <span class="quote">“<span class="quote">index</span>”</span> here refers to a position
              within the list of enumeration values. It has nothing to
              do with table indexes.
</p></li></ul>
</div>
<p>
          For example, a column specified as <code class="literal">ENUM('Mercury',
          'Venus', 'Earth')</code> can have any of the values shown
          here. The index of each value is also shown.
</p>
<div class="informaltable">
<table summary="Possible values for a column specified as ENUM('Mercury', 'Venus', 'Earth'). The table also shows the index of each value."><col width="15%"><col width="15%"><thead><tr>
              <th scope="col">Value</th>
              <th scope="col">Index</th>
            </tr></thead><tbody><tr>
              <td scope="row"><code class="literal">NULL</code></td>
              <td><code class="literal">NULL</code></td>
            </tr><tr>
              <td scope="row"><code class="literal">''</code></td>
              <td>0</td>
            </tr><tr>
              <td scope="row"><code class="literal">'Mercury'</code></td>
              <td>1</td>
            </tr><tr>
              <td scope="row"><code class="literal">'Venus'</code></td>
              <td>2</td>
            </tr><tr>
              <td scope="row"><code class="literal">'Earth'</code></td>
              <td>3</td>
</tr></tbody></table>
</div>
<p>
          An <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a> column can have a
          maximum of 65,535 distinct elements.
        </p><p>
          If you retrieve an <code class="literal">ENUM</code> value in a numeric
          context, the column value's index is returned. For example,
          you can retrieve numeric values from an
          <code class="literal">ENUM</code> column like this:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT <em class="replaceable"><code>enum_col</code></em>+0 FROM <em class="replaceable"><code>tbl_name</code></em>;</code></strong>
</pre><p>
          Functions such as <a class="link" href="functions.html#function_sum"><code class="literal">SUM()</code></a> or
          <a class="link" href="functions.html#function_avg"><code class="literal">AVG()</code></a> that expect a numeric
          argument cast the argument to a number if necessary. For
          <code class="literal">ENUM</code> values, the index number is used in
          the calculation.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-literals"></a>Handling of Enumeration Literals</h4>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336689040"></a><p>
          Trailing spaces are automatically deleted from
          <code class="literal">ENUM</code> member values in the table definition
          when a table is created.
        </p><p>
          When retrieved, values stored into an <code class="literal">ENUM</code>
          column are displayed using the lettercase that was used in the
          column definition. Note that <code class="literal">ENUM</code> columns
          can be assigned a character set and collation. For binary or
          case-sensitive collations, lettercase is taken into account
          when assigning values to the column.
        </p><p>
          If you store a number into an <code class="literal">ENUM</code> column,
          the number is treated as the index into the possible values,
          and the value stored is the enumeration member with that
          index. (However, this does <span class="emphasis"><em>not</em></span> work with
          <a class="link" href="sql-statements.html#load-data" title="13.2.7 LOAD DATA Statement"><code class="literal">LOAD DATA</code></a>, which treats all
          input as strings.) If the numeric value is quoted, it is still
          interpreted as an index if there is no matching string in the
          list of enumeration values. For these reasons, it is not
          advisable to define an <code class="literal">ENUM</code> column with
          enumeration values that look like numbers, because this can
          easily become confusing. For example, the following column has
          enumeration members with string values of
          <code class="literal">'0'</code>, <code class="literal">'1'</code>, and
          <code class="literal">'2'</code>, but numeric index values of
          <code class="literal">1</code>, <code class="literal">2</code>, and
          <code class="literal">3</code>:
        </p><pre data-lang="sql" class="programlisting">numbers ENUM('0','1','2')</pre><p>
          If you store <code class="literal">2</code>, it is interpreted as an
          index value, and becomes <code class="literal">'1'</code> (the value
          with index 2). If you store <code class="literal">'2'</code>, it matches
          an enumeration value, so it is stored as
          <code class="literal">'2'</code>. If you store <code class="literal">'3'</code>,
          it does not match any enumeration value, so it is treated as
          an index and becomes <code class="literal">'2'</code> (the value with
          index 3).
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO t (numbers) VALUES(2),('2'),('3');</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT * FROM t;</code></strong>
+---------+
| numbers |
+---------+
| 1       |
| 2       |
| 2       |
+---------+
</pre><p>
          To determine all possible values for an
          <code class="literal">ENUM</code> column, use
          <a class="link" href="sql-statements.html#show-columns" title="13.7.7.5 SHOW COLUMNS Statement"><code class="literal">SHOW COLUMNS
          FROM <em class="replaceable"><code>tbl_name</code></em> LIKE
          '<em class="replaceable"><code>enum_col</code></em>'</code></a> and parse the
          <code class="literal">ENUM</code> definition in the
          <code class="literal">Type</code> column of the output.
        </p><p>
          In the C API, <code class="literal">ENUM</code> values are returned as
          strings. For information about using result set metadata to
          distinguish them from other strings, see
          <a class="xref" href="connectors-apis.html#c-api-data-structures" title="28.7.4 C API Data Structures">Section 28.7.4, “C API Data Structures”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-nulls"></a>Empty or NULL Enumeration Values</h4>

</div>

</div>

</div>
<p>
          An enumeration value can also be the empty string
          (<code class="literal">''</code>) or <code class="literal">NULL</code> under
          certain circumstances:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              If you insert an invalid value into an
              <code class="literal">ENUM</code> (that is, a string not present in
              the list of permitted values), the empty string is
              inserted instead as a special error value. This string can
              be distinguished from a <span class="quote">“<span class="quote">normal</span>”</span> empty string
              by the fact that this string has the numeric value 0. See
              <a class="xref" href="data-types.html#enum-indexes" title="Index Values for Enumeration Literals">Index Values for Enumeration Literals</a> for details about the
              numeric indexes for the enumeration values.
            </p><p>
              If strict SQL mode is enabled, attempts to insert invalid
              <code class="literal">ENUM</code> values result in an error.
            </p></li><li class="listitem"><p>
              If an <code class="literal">ENUM</code> column is declared to permit
              <code class="literal">NULL</code>, the <code class="literal">NULL</code> value
              is a valid value for the column, and the default value is
              <code class="literal">NULL</code>. If an <code class="literal">ENUM</code>
              column is declared <code class="literal">NOT NULL</code>, its
              default value is the first element of the list of
              permitted values.
</p></li></ul>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-sorting"></a>Enumeration Sorting</h4>

</div>

</div>

</div>
<p>
          <code class="literal">ENUM</code> values are sorted based on their index
          numbers, which depend on the order in which the enumeration
          members were listed in the column specification. For example,
          <code class="literal">'b'</code> sorts before <code class="literal">'a'</code> for
          <code class="literal">ENUM('b', 'a')</code>. The empty string sorts
          before nonempty strings, and <code class="literal">NULL</code> values
          sort before all other enumeration values.
        </p><p>
          To prevent unexpected results when using the <code class="literal">ORDER
          BY</code> clause on an <code class="literal">ENUM</code> column, use
          one of these techniques:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              Specify the <code class="literal">ENUM</code> list in alphabetic
              order.
            </p></li><li class="listitem"><p>
              Make sure that the column is sorted lexically rather than
              by index number by coding <code class="literal">ORDER BY
              CAST(<em class="replaceable"><code>col</code></em> AS CHAR)</code> or
              <code class="literal">ORDER BY
              CONCAT(<em class="replaceable"><code>col</code></em>)</code>.
</p></li></ul>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="enum-limits"></a>Enumeration Limitations</h4>

</div>

</div>

</div>
<p>
          An enumeration value cannot be an expression, even one that
          evaluates to a string value.
        </p><p>
          For example, this <a class="link" href="sql-statements.html#create-table" title="13.1.20 CREATE TABLE Statement"><code class="literal">CREATE TABLE</code></a>
          statement does <span class="emphasis"><em>not</em></span> work because the
          <code class="literal">CONCAT</code> function cannot be used to construct
          an enumeration value:
        </p><pre data-lang="sql" class="programlisting">CREATE TABLE sizes (
    size ENUM('small', CONCAT('med','ium'), 'large')
);</pre><p>
          You also cannot employ a user variable as an enumeration
          value. This pair of statements do <span class="emphasis"><em>not</em></span>
          work:
        </p><pre data-lang="sql" class="programlisting">SET @mysize = 'medium';

CREATE TABLE sizes (
    size ENUM('small', @mysize, 'large')
);</pre><p>
          We strongly recommend that you do <span class="emphasis"><em>not</em></span> use
          numbers as enumeration values, because it does not save on
          storage over the appropriate
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a> or
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a> type, and it is easy
          to mix up the strings and the underlying number values (which
          might not be the same) if you quote the
          <code class="literal">ENUM</code> values incorrectly. If you do use a
          number as an enumeration value, always enclose it in quotation
          marks. If the quotation marks are omitted, the number is
          regarded as an index. See <a class="xref" href="data-types.html#enum-literals" title="Handling of Enumeration Literals">Handling of Enumeration Literals</a> to
          see how even a quoted number could be mistakenly used as a
          numeric index value.
        </p><p>
          Duplicate values in the definition cause a warning, or an
          error if strict SQL mode is enabled.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="set"></a>11.3.6 The SET Type</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336620384"></a><a class="indexterm" name="idm46444336619312"></a><p>
        A <code class="literal">SET</code> is a string object that can have zero
        or more values, each of which must be chosen from a list of
        permitted values specified when the table is created.
        <code class="literal">SET</code> column values that consist of multiple
        set members are specified with members separated by commas
        (<code class="literal">,</code>). A consequence of this is that
        <code class="literal">SET</code> member values should not themselves
        contain commas.
      </p><p>
        For example, a column specified as <code class="literal">SET('one', 'two')
        NOT NULL</code> can have any of these values:
      </p><pre data-lang="simple" class="programlisting">''
'one'
'two'
'one,two'</pre><p>
        A <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> column can have a maximum
        of 64 distinct members.
      </p><p>
        Duplicate values in the definition cause a warning, or an error
        if strict SQL mode is enabled.
      </p><a class="indexterm" name="idm46444336610032"></a><p>
        Trailing spaces are automatically deleted from
        <code class="literal">SET</code> member values in the table definition
        when a table is created.
      </p><p>
        When retrieved, values stored in a <code class="literal">SET</code> column
        are displayed using the lettercase that was used in the column
        definition. Note that <code class="literal">SET</code> columns can be
        assigned a character set and collation. For binary or
        case-sensitive collations, lettercase is taken into account when
        assigning values to the column.
      </p><p>
        MySQL stores <code class="literal">SET</code> values numerically, with the
        low-order bit of the stored value corresponding to the first set
        member. If you retrieve a <code class="literal">SET</code> value in a
        numeric context, the value retrieved has bits set corresponding
        to the set members that make up the column value. For example,
        you can retrieve numeric values from a <code class="literal">SET</code>
        column like this:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT <em class="replaceable"><code>set_col</code></em>+0 FROM <em class="replaceable"><code>tbl_name</code></em>;</code></strong>
</pre><p>
        If a number is stored into a <code class="literal">SET</code> column, the
        bits that are set in the binary representation of the number
        determine the set members in the column value. For a column
        specified as <code class="literal">SET('a','b','c','d')</code>, the
        members have the following decimal and binary values.
</p>
<div class="informaltable">
<table summary="Decimal and binary values for members of a column specified as SET('a','b','c','d')."><col width="15%"><col width="20%"><col width="20%"><thead><tr>
            <th scope="col"><code class="literal">SET</code> Member</th>
            <th scope="col">Decimal Value</th>
            <th scope="col">Binary Value</th>
          </tr></thead><tbody><tr>
            <td scope="row"><code class="literal">'a'</code></td>
            <td><code class="literal">1</code></td>
            <td><code class="literal">0001</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">'b'</code></td>
            <td><code class="literal">2</code></td>
            <td><code class="literal">0010</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">'c'</code></td>
            <td><code class="literal">4</code></td>
            <td><code class="literal">0100</code></td>
          </tr><tr>
            <td scope="row"><code class="literal">'d'</code></td>
            <td><code class="literal">8</code></td>
            <td><code class="literal">1000</code></td>
</tr></tbody></table>
</div>
<p>
        If you assign a value of <code class="literal">9</code> to this column,
        that is <code class="literal">1001</code> in binary, so the first and
        fourth <code class="literal">SET</code> value members
        <code class="literal">'a'</code> and <code class="literal">'d'</code> are selected
        and the resulting value is <code class="literal">'a,d'</code>.
      </p><p>
        For a value containing more than one <code class="literal">SET</code>
        element, it does not matter what order the elements are listed
        in when you insert the value. It also does not matter how many
        times a given element is listed in the value. When the value is
        retrieved later, each element in the value appears once, with
        elements listed according to the order in which they were
        specified at table creation time. Suppose that a column is
        specified as <code class="literal">SET('a','b','c','d')</code>:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));</code></strong>
</pre><p>
        If you insert the values <code class="literal">'a,d'</code>,
        <code class="literal">'d,a'</code>, <code class="literal">'a,d,d'</code>,
        <code class="literal">'a,d,a'</code>, and <code class="literal">'d,a,d'</code>:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO myset (col) VALUES </code></strong>
-&gt; ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');
Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0
</pre><p>
        Then all these values appear as <code class="literal">'a,d'</code> when
        retrieved:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT col FROM myset;</code></strong>
+------+
| col  |
+------+
| a,d  |
| a,d  |
| a,d  |
| a,d  |
| a,d  |
+------+
5 rows in set (0.04 sec)
</pre><p>
        If you set a <code class="literal">SET</code> column to an unsupported
        value, the value is ignored and a warning is issued:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO myset (col) VALUES ('a,d,d,s');</code></strong>
Query OK, 1 row affected, 1 warning (0.03 sec)

mysql&gt; <strong class="userinput"><code>SHOW WARNINGS;</code></strong>
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'col' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.04 sec)

mysql&gt; <strong class="userinput"><code>SELECT col FROM myset;</code></strong>
+------+
| col  |
+------+
| a,d  |
| a,d  |
| a,d  |
| a,d  |
| a,d  |
| a,d  |
+------+
6 rows in set (0.01 sec)
</pre><p>
        If strict SQL mode is enabled, attempts to insert invalid
        <code class="literal">SET</code> values result in an error.
      </p><p>
        <code class="literal">SET</code> values are sorted numerically.
        <code class="literal">NULL</code> values sort before
        non-<code class="literal">NULL</code> <code class="literal">SET</code> values.
      </p><p>
        Functions such as <a class="link" href="functions.html#function_sum"><code class="literal">SUM()</code></a> or
        <a class="link" href="functions.html#function_avg"><code class="literal">AVG()</code></a> that expect a numeric
        argument cast the argument to a number if necessary. For
        <code class="literal">SET</code> values, the cast operation causes the
        numeric value to be used.
      </p><p>
        Normally, you search for <code class="literal">SET</code> values using the
        <a class="link" href="functions.html#function_find-in-set"><code class="literal">FIND_IN_SET()</code></a> function or the
        <a class="link" href="functions.html#operator_like"><code class="literal">LIKE</code></a> operator:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT * FROM <em class="replaceable"><code>tbl_name</code></em> WHERE FIND_IN_SET('<em class="replaceable"><code>value</code></em>',<em class="replaceable"><code>set_col</code></em>)&gt;0;</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT * FROM <em class="replaceable"><code>tbl_name</code></em> WHERE <em class="replaceable"><code>set_col</code></em> LIKE '%<em class="replaceable"><code>value</code></em>%';</code></strong>
</pre><p>
        The first statement finds rows where
        <em class="replaceable"><code>set_col</code></em> contains the
        <em class="replaceable"><code>value</code></em> set member. The second is
        similar, but not the same: It finds rows where
        <em class="replaceable"><code>set_col</code></em> contains
        <em class="replaceable"><code>value</code></em> anywhere, even as a substring
        of another set member.
      </p><p>
        The following statements also are permitted:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT * FROM <em class="replaceable"><code>tbl_name</code></em> WHERE <em class="replaceable"><code>set_col</code></em> &amp; 1;</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT * FROM <em class="replaceable"><code>tbl_name</code></em> WHERE <em class="replaceable"><code>set_col</code></em> = '<em class="replaceable"><code>val1</code></em>,<em class="replaceable"><code>val2</code></em>';</code></strong>
</pre><p>
        The first of these statements looks for values containing the
        first set member. The second looks for an exact match. Be
        careful with comparisons of the second type. Comparing set
        values to
        <code class="literal">'<em class="replaceable"><code>val1</code></em>,<em class="replaceable"><code>val2</code></em>'</code>
        returns different results than comparing values to
        <code class="literal">'<em class="replaceable"><code>val2</code></em>,<em class="replaceable"><code>val1</code></em>'</code>.
        You should specify the values in the same order they are listed
        in the column definition.
      </p><p>
        To determine all possible values for a <code class="literal">SET</code>
        column, use <code class="literal">SHOW COLUMNS FROM
        <em class="replaceable"><code>tbl_name</code></em> LIKE
        <em class="replaceable"><code>set_col</code></em></code> and parse the
        <code class="literal">SET</code> definition in the <code class="literal">Type</code>
        column of the output.
      </p><p>
        In the C API, <code class="literal">SET</code> values are returned as
        strings. For information about using result set metadata to
        distinguish them from other strings, see
        <a class="xref" href="connectors-apis.html#c-api-data-structures" title="28.7.4 C API Data Structures">Section 28.7.4, “C API Data Structures”</a>.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="spatial-types"></a>11.4 Spatial Data Types</h2>

</div>

</div>

</div>
<div class="toc">
<dl class="toc"><dt><span class="section"><a href="data-types.html#spatial-type-overview">11.4.1 Spatial Data Types</a></span></dt><dt><span class="section"><a href="data-types.html#opengis-geometry-model">11.4.2 The OpenGIS Geometry Model</a></span></dt><dt><span class="section"><a href="data-types.html#gis-data-formats">11.4.3 Supported Spatial Data Formats</a></span></dt><dt><span class="section"><a href="data-types.html#geometry-well-formedness-validity">11.4.4 Geometry Well-Formedness and Validity</a></span></dt><dt><span class="section"><a href="data-types.html#spatial-reference-systems">11.4.5 Spatial Reference System Support</a></span></dt><dt><span class="section"><a href="data-types.html#creating-spatial-columns">11.4.6 Creating Spatial Columns</a></span></dt><dt><span class="section"><a href="data-types.html#populating-spatial-columns">11.4.7 Populating Spatial Columns</a></span></dt><dt><span class="section"><a href="data-types.html#fetching-spatial-data">11.4.8 Fetching Spatial Data</a></span></dt><dt><span class="section"><a href="data-types.html#optimizing-spatial-analysis">11.4.9 Optimizing Spatial Analysis</a></span></dt><dt><span class="section"><a href="data-types.html#creating-spatial-indexes">11.4.10 Creating Spatial Indexes</a></span></dt><dt><span class="section"><a href="data-types.html#using-spatial-indexes">11.4.11 Using Spatial Indexes</a></span></dt></dl>
</div>
<a class="indexterm" name="idm46444336513536"></a><a class="indexterm" name="idm46444336512464"></a><a class="indexterm" name="idm46444336511376"></a><a class="indexterm" name="idm46444336510288"></a><a class="indexterm" name="idm46444336509216"></a><a class="indexterm" name="idm46444336508128"></a><p>
      The <a class="ulink" href="http://www.opengeospatial.org" target="_top">Open Geospatial
      Consortium</a> (OGC) is an international consortium of more
      than 250 companies, agencies, and universities participating in
      the development of publicly available conceptual solutions that
      can be useful with all kinds of applications that manage spatial
      data.
    </p><p>
      The Open Geospatial Consortium publishes the
      <em class="citetitle">OpenGIS® Implementation Standard for Geographic
      information - Simple feature access - Part 2: SQL
      option</em>, a document that proposes several conceptual
      ways for extending an SQL RDBMS to support spatial data. This
      specification is available from the OGC website at
      <a class="ulink" href="http://www.opengeospatial.org/standards/sfs" target="_top">http://www.opengeospatial.org/standards/sfs</a>.
    </p><p>
      Following the OGC specification, MySQL implements spatial
      extensions as a subset of the <span class="bold"><strong>SQL with
      Geometry Types</strong></span> environment. This term refers to an SQL
      environment that has been extended with a set of geometry types. A
      geometry-valued SQL column is implemented as a column that has a
      geometry type. The specification describes a set of SQL geometry
      types, as well as functions on those types to create and analyze
      geometry values.
    </p><p>
      MySQL spatial extensions enable the generation, storage, and
      analysis of geographic features:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          Data types for representing spatial values
        </p></li><li class="listitem"><p>
          Functions for manipulating spatial values
        </p></li><li class="listitem"><p>
          Spatial indexing for improved access times to spatial columns
</p></li></ul>
</div>
<p>
      The spatial data types and functions are available for
      <a class="link" href="storage-engines.html#myisam-storage-engine" title="16.2 The MyISAM Storage Engine"><code class="literal">MyISAM</code></a>,
      <a class="link" href="innodb-storage-engine.html" title="Chapter 15 The InnoDB Storage Engine"><code class="literal">InnoDB</code></a>,
      <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a>, and
      <a class="link" href="storage-engines.html#archive-storage-engine" title="16.5 The ARCHIVE Storage Engine"><code class="literal">ARCHIVE</code></a> tables. For indexing spatial
      columns, <code class="literal">MyISAM</code> and <code class="literal">InnoDB</code>
      support both <code class="literal">SPATIAL</code> and
      non-<code class="literal">SPATIAL</code> indexes. The other storage engines
      support non-<code class="literal">SPATIAL</code> indexes, as described in
      <a class="xref" href="sql-statements.html#create-index" title="13.1.15 CREATE INDEX Statement">Section 13.1.15, “CREATE INDEX Statement”</a>.
    </p><a class="indexterm" name="idm46444336487408"></a><p>
      A <span class="bold"><strong>geographic feature</strong></span> is anything
      in the world that has a location. A feature can be:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          An entity. For example, a mountain, a pond, a city.
        </p></li><li class="listitem"><p>
          A space. For example, town district, the tropics.
        </p></li><li class="listitem"><p>
          A definable location. For example, a crossroad, as a
          particular place where two streets intersect.
</p></li></ul>
</div>
<a class="indexterm" name="idm46444336482144"></a><p>
      Some documents use the term <span class="bold"><strong>geospatial
      feature</strong></span> to refer to geographic features.
    </p><a class="indexterm" name="idm46444336479888"></a><p>
      <span class="bold"><strong>Geometry</strong></span> is another word that
      denotes a geographic feature. Originally the word
      <span class="bold"><strong>geometry</strong></span> meant measurement of the
      earth. Another meaning comes from cartography, referring to the
      geometric features that cartographers use to map the world.
    </p><p>
      The discussion here considers these terms synonymous:
      <span class="bold"><strong>geographic feature</strong></span>,
      <span class="bold"><strong>geospatial feature</strong></span>,
      <span class="bold"><strong>feature</strong></span>, or
      <span class="bold"><strong>geometry</strong></span>. The term most commonly
      used is <span class="bold"><strong>geometry</strong></span>, defined as
      <span class="emphasis"><em>a point or an aggregate of points representing anything
      in the world that has a location</em></span>.
    </p><p>
      The following material covers these topics:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          The spatial data types implemented in MySQL model
        </p></li><li class="listitem"><p>
          The basis of the spatial extensions in the OpenGIS geometry
          model
        </p></li><li class="listitem"><p>
          Data formats for representing spatial data
        </p></li><li class="listitem"><p>
          How to use spatial data in MySQL
        </p></li><li class="listitem"><p>
          Use of indexing for spatial data
        </p></li><li class="listitem"><p>
          MySQL differences from the OpenGIS specification
</p></li></ul>
</div>
<p>
      For information about functions that operate on spatial data, see
      <a class="xref" href="functions.html#spatial-analysis-functions" title="12.16 Spatial Analysis Functions">Section 12.16, “Spatial Analysis Functions”</a>.
</p>
<h3><a name="idm46444336464848"></a>Additional Resources</h3>
<p>
      These standards are important for the MySQL implementation of
      spatial operations:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          SQL/MM Part 3: Spatial.
        </p></li><li class="listitem"><p>
          The <a class="ulink" href="http://www.opengeospatial.org" target="_top">Open Geospatial
          Consortium</a> publishes the <em class="citetitle">OpenGIS®
          Implementation Standard for Geographic
          information</em>, a document that proposes several
          conceptual ways for extending an SQL RDBMS to support spatial
          data. See in particular Simple Feature Access - Part 1: Common
          Architecture, and Simple Feature Access - Part 2: SQL Option.
          The Open Geospatial Consortium (OGC) maintains a website at
          <a class="ulink" href="http://www.opengeospatial.org/" target="_top">http://www.opengeospatial.org/</a>. The
          specification is available there at
          <a class="ulink" href="http://www.opengeospatial.org/standards/sfs" target="_top">http://www.opengeospatial.org/standards/sfs</a>. It
          contains additional information relevant to the material here.
        </p></li><li class="listitem"><p>
          The grammar for
          <a class="link" href="data-types.html#spatial-reference-systems" title="11.4.5 Spatial Reference System Support">spatial reference
          system</a> (SRS) definitions is based on the grammar
          defined in <em class="citetitle">OpenGIS Implementation Specification:
          Coordinate Transformation Services</em>, Revision 1.00,
          OGC 01-009, January 12, 2001, Section 7.2. This specification
          is available at
          <a class="ulink" href="http://www.opengeospatial.org/standards/ct" target="_top">http://www.opengeospatial.org/standards/ct</a>. For
          differences from that specification in SRS definitions as
          implemented in MySQL, see
          <a class="xref" href="sql-statements.html#create-spatial-reference-system" title="13.1.19 CREATE SPATIAL REFERENCE SYSTEM Statement">Section 13.1.19, “CREATE SPATIAL REFERENCE SYSTEM Statement”</a>.
</p></li></ul>
</div>
<p>
      If you have questions or concerns about the use of the spatial
      extensions to MySQL, you can discuss them in the GIS forum:
      <a class="ulink" href="https://forums.mysql.com/list.php?23" target="_top">https://forums.mysql.com/list.php?23</a>.
</p>
<div class="section">

<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="spatial-type-overview"></a>11.4.1 Spatial Data Types</h3>
</div>
</div>
</div>
<a class="indexterm" name="idm46444336452528"></a><a class="indexterm" name="idm46444336451456"></a><a class="indexterm" name="idm46444336450384"></a><a class="indexterm" name="idm46444336449312"></a><a class="indexterm" name="idm46444336448240"></a><a class="indexterm" name="idm46444336447168"></a><a class="indexterm" name="idm46444336446080"></a><a class="indexterm" name="idm46444336445008"></a><a class="indexterm" name="idm46444336443920"></a><a class="indexterm" name="idm46444336442432"></a><a class="indexterm" name="idm46444336440944"></a><a class="indexterm" name="idm46444336439456"></a><a class="indexterm" name="idm46444336437968"></a><a class="indexterm" name="idm46444336436480"></a><a class="indexterm" name="idm46444336434992"></a><a class="indexterm" name="idm46444336433504"></a><a class="indexterm" name="idm46444336432016"></a><a class="indexterm" name="idm46444336430528"></a><p>
        MySQL has spatial data types that correspond to OpenGIS classes.
        The basis for these types is described in
        <a class="xref" href="data-types.html#opengis-geometry-model" title="11.4.2 The OpenGIS Geometry Model">Section 11.4.2, “The OpenGIS Geometry Model”</a>.
      </p><p>
        Some spatial data types hold single geometry values:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">GEOMETRY</code>
          </p></li><li class="listitem"><p>
            <code class="literal">POINT</code>
          </p></li><li class="listitem"><p>
            <code class="literal">LINESTRING</code>
          </p></li><li class="listitem"><p>
            <code class="literal">POLYGON</code>
</p></li></ul>
</div>
<p>
        <code class="literal">GEOMETRY</code> can store geometry values of any
        type. The other single-value types (<code class="literal">POINT</code>,
        <code class="literal">LINESTRING</code>, and <code class="literal">POLYGON</code>)
        restrict their values to a particular geometry type.
      </p><p>
        The other spatial data types hold collections of values:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">MULTIPOINT</code>
          </p></li><li class="listitem"><p>
            <code class="literal">MULTILINESTRING</code>
          </p></li><li class="listitem"><p>
            <code class="literal">MULTIPOLYGON</code>
          </p></li><li class="listitem"><p>
            <code class="literal">GEOMETRYCOLLECTION</code>
</p></li></ul>
</div>
<p>
        <code class="literal">GEOMETRYCOLLECTION</code> can store a collection of
        objects of any type. The other collection types
        (<code class="literal">MULTIPOINT</code>,
        <code class="literal">MULTILINESTRING</code>, and
        <code class="literal">MULTIPOLYGON</code>) restrict collection members to
        those having a particular geometry type.
      </p><p>
        Example: To create a table named <code class="literal">geom</code> that
        has a column named <code class="literal">g</code> that can store values of
        any geometry type, use this statement:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY);</pre><p>
        Columns with a spatial data type can have an
        <code class="literal">SRID</code> attribute, to explicitly indicate the
        spatial reference system (SRS) for values stored in the column.
        For example:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (
    p POINT SRID 0,
    g GEOMETRY NOT NULL SRID 4326
);</pre><p>
        <code class="literal">SPATIAL</code> indexes can be created on spatial
        columns if they are <code class="literal">NOT NULL</code> and have a
        specific SRID, so if you plan to index the column, declare it
        with the <code class="literal">NOT NULL</code> and <code class="literal">SRID</code>
        attributes:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326);</pre><p>
        <code class="literal">InnoDB</code> tables permit <code class="literal">SRID</code>
        values for Cartesian and geographic SRSs.
        <code class="literal">MyISAM</code> tables permit <code class="literal">SRID</code>
        values for Cartesian SRSs.
      </p><p>
        The <code class="literal">SRID</code> attribute makes a spatial column
        SRID-restricted, which has these implications:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            The column can contain only values with the given SRID.
            Attempts to insert values with a different SRID produce an
            error.
          </p></li><li class="listitem"><p>
            The optimizer can use <code class="literal">SPATIAL</code> indexes on
            the column. See
            <a class="xref" href="optimization.html#spatial-index-optimization" title="8.3.3 SPATIAL Index Optimization">Section 8.3.3, “SPATIAL Index Optimization”</a>.
</p></li></ul>
</div>
<p>
        Spatial columns with no <code class="literal">SRID</code> attribute are
        not SRID-restricted and accept values with any SRID. However,
        the optimizer cannot use <code class="literal">SPATIAL</code> indexes on
        them until the column definition is modified to include an
        <code class="literal">SRID</code> attribute, which may require that the
        column contents first be modified so that all values have the
        same SRID.
      </p><p>
        For other examples showing how to use spatial data types in
        MySQL, see <a class="xref" href="data-types.html#creating-spatial-columns" title="11.4.6 Creating Spatial Columns">Section 11.4.6, “Creating Spatial Columns”</a>. For
        information about spatial reference systems, see
        <a class="xref" href="data-types.html#spatial-reference-systems" title="11.4.5 Spatial Reference System Support">Section 11.4.5, “Spatial Reference System Support”</a>.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="opengis-geometry-model"></a>11.4.2 The OpenGIS Geometry Model</h3>

</div>

</div>

</div>
<div class="toc">
<dl class="toc"><dt><span class="section"><a href="data-types.html#gis-geometry-class-hierarchy">11.4.2.1 The Geometry Class Hierarchy</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-geometry">11.4.2.2 Geometry Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-point">11.4.2.3 Point Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-curve">11.4.2.4 Curve Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-linestring">11.4.2.5 LineString Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-surface">11.4.2.6 Surface Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-polygon">11.4.2.7 Polygon Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-geometrycollection">11.4.2.8 GeometryCollection Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-multipoint">11.4.2.9 MultiPoint Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-multicurve">11.4.2.10 MultiCurve Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-multilinestring">11.4.2.11 MultiLineString Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-multisurface">11.4.2.12 MultiSurface Class</a></span></dt><dt><span class="section"><a href="data-types.html#gis-class-multipolygon">11.4.2.13 MultiPolygon Class</a></span></dt></dl>
</div>
<p>
        The set of geometry types proposed by OGC's
        <span class="bold"><strong>SQL with Geometry Types</strong></span>
        environment is based on the <span class="bold"><strong>OpenGIS
        Geometry Model</strong></span>. In this model, each geometric object
        has the following general properties:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            It is associated with a spatial reference system, which
            describes the coordinate space in which the object is
            defined.
          </p></li><li class="listitem"><p>
            It belongs to some geometry class.
</p></li></ul>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-geometry-class-hierarchy"></a>11.4.2.1 The Geometry Class Hierarchy</h4>

</div>

</div>

</div>
<p>
          The geometry classes define a hierarchy as follows:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              <code class="literal">Geometry</code> (noninstantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                  <code class="literal">Point</code> (instantiable)
                </p></li><li class="listitem"><p>
                  <code class="literal">Curve</code> (noninstantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: square; "><li class="listitem"><p>
                      <code class="literal">LineString</code> (instantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
                          <code class="literal">Line</code>
                        </p></li><li class="listitem"><p>
                          <code class="literal">LinearRing</code>
</p></li></ul>
</div>
</li></ul>
</div>
</li><li class="listitem"><p>
                  <code class="literal">Surface</code> (noninstantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: square; "><li class="listitem"><p>
                      <code class="literal">Polygon</code> (instantiable)
</p></li></ul>
</div>
</li><li class="listitem"><p>
                  <code class="literal">GeometryCollection</code> (instantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: square; "><li class="listitem"><p>
                      <code class="literal">MultiPoint</code> (instantiable)
                    </p></li><li class="listitem"><p>
                      <code class="literal">MultiCurve</code> (noninstantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
                          <code class="literal">MultiLineString</code>
                          (instantiable)
</p></li></ul>
</div>
</li><li class="listitem"><p>
                      <code class="literal">MultiSurface</code> (noninstantiable)
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
                          <code class="literal">MultiPolygon</code> (instantiable)
</p></li></ul>
</div>
</li></ul>
</div>
</li></ul>
</div>
</li></ul>
</div>
<p>
          It is not possible to create objects in noninstantiable
          classes. It is possible to create objects in instantiable
          classes. All classes have properties, and instantiable classes
          may also have assertions (rules that define valid class
          instances).
        </p><p>
          <code class="literal">Geometry</code> is the base class. It is an
          abstract class. The instantiable subclasses of
          <code class="literal">Geometry</code> are restricted to zero-, one-, and
          two-dimensional geometric objects that exist in
          two-dimensional coordinate space. All instantiable geometry
          classes are defined so that valid instances of a geometry
          class are topologically closed (that is, all defined
          geometries include their boundary).
        </p><p>
          The base <code class="literal">Geometry</code> class has subclasses for
          <code class="literal">Point</code>, <code class="literal">Curve</code>,
          <code class="literal">Surface</code>, and
          <code class="literal">GeometryCollection</code>:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              <code class="literal">Point</code> represents zero-dimensional
              objects.
            </p></li><li class="listitem"><p>
              <code class="literal">Curve</code> represents one-dimensional
              objects, and has subclass <code class="literal">LineString</code>,
              with sub-subclasses <code class="literal">Line</code> and
              <code class="literal">LinearRing</code>.
            </p></li><li class="listitem"><p>
              <code class="literal">Surface</code> is designed for two-dimensional
              objects and has subclass <code class="literal">Polygon</code>.
            </p></li><li class="listitem"><p>
              <code class="literal">GeometryCollection</code> has specialized
              zero-, one-, and two-dimensional collection classes named
              <code class="literal">MultiPoint</code>,
              <code class="literal">MultiLineString</code>, and
              <code class="literal">MultiPolygon</code> for modeling geometries
              corresponding to collections of <code class="literal">Points</code>,
              <code class="literal">LineStrings</code>, and
              <code class="literal">Polygons</code>, respectively.
              <code class="literal">MultiCurve</code> and
              <code class="literal">MultiSurface</code> are introduced as abstract
              superclasses that generalize the collection interfaces to
              handle <code class="literal">Curves</code> and
              <code class="literal">Surfaces</code>.
</p></li></ul>
</div>
<p>
          <code class="literal">Geometry</code>, <code class="literal">Curve</code>,
          <code class="literal">Surface</code>, <code class="literal">MultiCurve</code>, and
          <code class="literal">MultiSurface</code> are defined as noninstantiable
          classes. They define a common set of methods for their
          subclasses and are included for extensibility.
        </p><p>
          <code class="literal">Point</code>, <code class="literal">LineString</code>,
          <code class="literal">Polygon</code>,
          <code class="literal">GeometryCollection</code>,
          <code class="literal">MultiPoint</code>,
          <code class="literal">MultiLineString</code>, and
          <code class="literal">MultiPolygon</code> are instantiable classes.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-geometry"></a>11.4.2.2 Geometry Class</h4>

</div>

</div>

</div>
<p>
          <code class="literal">Geometry</code> is the root class of the
          hierarchy. It is a noninstantiable class but has a number of
          properties, described in the following list, that are common
          to all geometry values created from any of the
          <code class="literal">Geometry</code> subclasses. Particular subclasses
          have their own specific properties, described later.
        </p><p>
          <span class="bold"><strong>Geometry Properties</strong></span>
        </p><p>
          A geometry value has the following properties:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              Its <span class="bold"><strong>type</strong></span>. Each geometry
              belongs to one of the instantiable classes in the
              hierarchy.
            </p></li><li class="listitem"><p>
              Its <span class="bold"><strong>SRID</strong></span>, or spatial
              reference identifier. This value identifies the geometry's
              associated spatial reference system that describes the
              coordinate space in which the geometry object is defined.
            </p><p>
              In MySQL, the SRID value is an integer associated with the
              geometry value. The maximum usable SRID value is
              2<sup>32</sup>−1. If a larger value
              is given, only the lower 32 bits are used.
            </p><p>
              SRID 0 represents an infinite flat Cartesian plane with no
              units assigned to its axes. To ensure SRID 0 behavior,
              create geometry values using SRID 0. SRID 0 is the default
              for new geometry values if no SRID is specified.
            </p><p>
              For computations on multiple geometry values, all values
              must have the same SRID or an error occurs.
            </p></li><li class="listitem"><p>
              Its <span class="bold"><strong>coordinates</strong></span> in its
              spatial reference system, represented as double-precision
              (8-byte) numbers. All nonempty geometries include at least
              one pair of (X,Y) coordinates. Empty geometries contain no
              coordinates.
            </p><p>
              Coordinates are related to the SRID. For example, in
              different coordinate systems, the distance between two
              objects may differ even when objects have the same
              coordinates, because the distance on the
              <span class="bold"><strong>planar</strong></span> coordinate system
              and the distance on the
              <span class="bold"><strong>geodetic</strong></span> system
              (coordinates on the Earth's surface) are different things.
            </p></li><li class="listitem"><p>
              Its <span class="bold"><strong>interior</strong></span>,
              <span class="bold"><strong>boundary</strong></span>, and
              <span class="bold"><strong>exterior</strong></span>.
            </p><p>
              Every geometry occupies some position in space. The
              exterior of a geometry is all space not occupied by the
              geometry. The interior is the space occupied by the
              geometry. The boundary is the interface between the
              geometry's interior and exterior.
            </p></li><li class="listitem"><p>
              Its <span class="bold"><strong>MBR</strong></span> (minimum bounding
              rectangle), or envelope. This is the bounding geometry,
              formed by the minimum and maximum (X,Y) coordinates:
            </p><pre data-lang="simple" class="programlisting">((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))</pre></li><li class="listitem"><p>
              Whether the value is
              <span class="bold"><strong>simple</strong></span> or
              <span class="bold"><strong>nonsimple</strong></span>. Geometry
              values of types (<code class="literal">LineString</code>,
              <code class="literal">MultiPoint</code>,
              <code class="literal">MultiLineString</code>) are either simple or
              nonsimple. Each type determines its own assertions for
              being simple or nonsimple.
            </p></li><li class="listitem"><p>
              Whether the value is
              <span class="bold"><strong>closed</strong></span> or
              <span class="bold"><strong>not closed</strong></span>. Geometry
              values of types (<code class="literal">LineString</code>,
              <code class="literal">MultiString</code>) are either closed or not
              closed. Each type determines its own assertions for being
              closed or not closed.
            </p></li><li class="listitem"><p>
              Whether the value is
              <span class="bold"><strong>empty</strong></span> or
              <span class="bold"><strong>nonempty</strong></span> A geometry is
              empty if it does not have any points. Exterior, interior,
              and boundary of an empty geometry are not defined (that
              is, they are represented by a <code class="literal">NULL</code>
              value). An empty geometry is defined to be always simple
              and has an area of 0.
            </p></li><li class="listitem"><p>
              Its <span class="bold"><strong>dimension</strong></span>. A geometry
              can have a dimension of −1, 0, 1, or 2:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                  −1 for an empty geometry.
                </p></li><li class="listitem"><p>
                  0 for a geometry with no length and no area.
                </p></li><li class="listitem"><p>
                  1 for a geometry with nonzero length and zero area.
                </p></li><li class="listitem"><p>
                  2 for a geometry with nonzero area.
</p></li></ul>
</div>
<p>
              <code class="literal">Point</code> objects have a dimension of zero.
              <code class="literal">LineString</code> objects have a dimension of
              1. <code class="literal">Polygon</code> objects have a dimension of
              2. The dimensions of <code class="literal">MultiPoint</code>,
              <code class="literal">MultiLineString</code>, and
              <code class="literal">MultiPolygon</code> objects are the same as
              the dimensions of the elements they consist of.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-point"></a>11.4.2.3 Point Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">Point</code> is a geometry that represents a
          single location in coordinate space.
        </p><p>
          <span class="bold"><strong><code class="literal">Point</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              Imagine a large-scale map of the world with many cities. A
              <code class="literal">Point</code> object could represent each city.
            </p></li><li class="listitem"><p>
              On a city map, a <code class="literal">Point</code> object could
              represent a bus stop.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">Point</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              X-coordinate value.
            </p></li><li class="listitem"><p>
              Y-coordinate value.
            </p></li><li class="listitem"><p>
              <code class="literal">Point</code> is defined as a zero-dimensional
              geometry.
            </p></li><li class="listitem"><p>
              The boundary of a <code class="literal">Point</code> is the empty
              set.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-curve"></a>11.4.2.4 Curve Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">Curve</code> is a one-dimensional geometry,
          usually represented by a sequence of points. Particular
          subclasses of <code class="literal">Curve</code> define the type of
          interpolation between points. <code class="literal">Curve</code> is a
          noninstantiable class.
        </p><p>
          <span class="bold"><strong><code class="literal">Curve</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">Curve</code> has the coordinates of its
              points.
            </p></li><li class="listitem"><p>
              A <code class="literal">Curve</code> is defined as a one-dimensional
              geometry.
            </p></li><li class="listitem"><p>
              A <code class="literal">Curve</code> is simple if it does not pass
              through the same point twice, with the exception that a
              curve can still be simple if the start and end points are
              the same.
            </p></li><li class="listitem"><p>
              A <code class="literal">Curve</code> is closed if its start point is
              equal to its endpoint.
            </p></li><li class="listitem"><p>
              The boundary of a closed <code class="literal">Curve</code> is
              empty.
            </p></li><li class="listitem"><p>
              The boundary of a nonclosed <code class="literal">Curve</code>
              consists of its two endpoints.
            </p></li><li class="listitem"><p>
              A <code class="literal">Curve</code> that is simple and closed is a
              <code class="literal">LinearRing</code>.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-linestring"></a>11.4.2.5 LineString Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">LineString</code> is a <code class="literal">Curve</code>
          with linear interpolation between points.
        </p><p>
          <span class="bold"><strong><code class="literal">LineString</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              On a world map, <code class="literal">LineString</code> objects
              could represent rivers.
            </p></li><li class="listitem"><p>
              In a city map, <code class="literal">LineString</code> objects could
              represent streets.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">LineString</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">LineString</code> has coordinates of
              segments, defined by each consecutive pair of points.
            </p></li><li class="listitem"><p>
              A <code class="literal">LineString</code> is a
              <code class="literal">Line</code> if it consists of exactly two
              points.
            </p></li><li class="listitem"><p>
              A <code class="literal">LineString</code> is a
              <code class="literal">LinearRing</code> if it is both closed and
              simple.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-surface"></a>11.4.2.6 Surface Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">Surface</code> is a two-dimensional geometry. It
          is a noninstantiable class. Its only instantiable subclass is
          <code class="literal">Polygon</code>.
        </p><p>
          <span class="bold"><strong><code class="literal">Surface</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">Surface</code> is defined as a
              two-dimensional geometry.
            </p></li><li class="listitem"><p>
              The OpenGIS specification defines a simple
              <code class="literal">Surface</code> as a geometry that consists of
              a single <span class="quote">“<span class="quote">patch</span>”</span> that is associated with a
              single exterior boundary and zero or more interior
              boundaries.
            </p></li><li class="listitem"><p>
              The boundary of a simple <code class="literal">Surface</code> is the
              set of closed curves corresponding to its exterior and
              interior boundaries.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-polygon"></a>11.4.2.7 Polygon Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">Polygon</code> is a planar
          <code class="literal">Surface</code> representing a multisided geometry.
          It is defined by a single exterior boundary and zero or more
          interior boundaries, where each interior boundary defines a
          hole in the <code class="literal">Polygon</code>.
        </p><p>
          <span class="bold"><strong><code class="literal">Polygon</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              On a region map, <code class="literal">Polygon</code> objects could
              represent forests, districts, and so on.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">Polygon</code>
          Assertions</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              The boundary of a <code class="literal">Polygon</code> consists of a
              set of <code class="literal">LinearRing</code> objects (that is,
              <code class="literal">LineString</code> objects that are both simple
              and closed) that make up its exterior and interior
              boundaries.
            </p></li><li class="listitem"><p>
              A <code class="literal">Polygon</code> has no rings that cross. The
              rings in the boundary of a <code class="literal">Polygon</code> may
              intersect at a <code class="literal">Point</code>, but only as a
              tangent.
            </p></li><li class="listitem"><p>
              A <code class="literal">Polygon</code> has no lines, spikes, or
              punctures.
            </p></li><li class="listitem"><p>
              A <code class="literal">Polygon</code> has an interior that is a
              connected point set.
            </p></li><li class="listitem"><p>
              A <code class="literal">Polygon</code> may have holes. The exterior
              of a <code class="literal">Polygon</code> with holes is not
              connected. Each hole defines a connected component of the
              exterior.
</p></li></ul>
</div>
<p>
          The preceding assertions make a <code class="literal">Polygon</code> a
          simple geometry.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-geometrycollection"></a>11.4.2.8 GeometryCollection Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">GeomCollection</code> is a geometry that is a
          collection of zero or more geometries of any class.
        </p><p>
          <code class="literal">GeomCollection</code> and
          <code class="literal">GeometryCollection</code> are synonymous, with
          <code class="literal">GeomCollection</code> the preferred type name.
        </p><p>
          All the elements in a geometry collection must be in the same
          spatial reference system (that is, in the same coordinate
          system). There are no other constraints on the elements of a
          geometry collection, although the subclasses of
          <code class="literal">GeomCollection</code> described in the following
          sections may restrict membership. Restrictions may be based
          on:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              Element type (for example, a <code class="literal">MultiPoint</code>
              may contain only <code class="literal">Point</code> elements)
            </p></li><li class="listitem"><p>
              Dimension
            </p></li><li class="listitem"><p>
              Constraints on the degree of spatial overlap between
              elements
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-multipoint"></a>11.4.2.9 MultiPoint Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">MultiPoint</code> is a geometry collection
          composed of <code class="literal">Point</code> elements. The points are
          not connected or ordered in any way.
        </p><p>
          <span class="bold"><strong><code class="literal">MultiPoint</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              On a world map, a <code class="literal">MultiPoint</code> could
              represent a chain of small islands.
            </p></li><li class="listitem"><p>
              On a city map, a <code class="literal">MultiPoint</code> could
              represent the outlets for a ticket office.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">MultiPoint</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">MultiPoint</code> is a zero-dimensional
              geometry.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiPoint</code> is simple if no two of its
              <code class="literal">Point</code> values are equal (have identical
              coordinate values).
            </p></li><li class="listitem"><p>
              The boundary of a <code class="literal">MultiPoint</code> is the
              empty set.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-multicurve"></a>11.4.2.10 MultiCurve Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">MultiCurve</code> is a geometry collection
          composed of <code class="literal">Curve</code> elements.
          <code class="literal">MultiCurve</code> is a noninstantiable class.
        </p><p>
          <span class="bold"><strong><code class="literal">MultiCurve</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">MultiCurve</code> is a one-dimensional
              geometry.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiCurve</code> is simple if and only if
              all of its elements are simple; the only intersections
              between any two elements occur at points that are on the
              boundaries of both elements.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiCurve</code> boundary is obtained by
              applying the <span class="quote">“<span class="quote">mod 2 union rule</span>”</span> (also known
              as the <span class="quote">“<span class="quote">odd-even rule</span>”</span>): A point is in the
              boundary of a <code class="literal">MultiCurve</code> if it is in
              the boundaries of an odd number of
              <code class="literal">Curve</code> elements.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiCurve</code> is closed if all of its
              elements are closed.
            </p></li><li class="listitem"><p>
              The boundary of a closed <code class="literal">MultiCurve</code> is
              always empty.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-multilinestring"></a>11.4.2.11 MultiLineString Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">MultiLineString</code> is a
          <code class="literal">MultiCurve</code> geometry collection composed of
          <code class="literal">LineString</code> elements.
        </p><p>
          <span class="bold"><strong><code class="literal">MultiLineString</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              On a region map, a <code class="literal">MultiLineString</code>
              could represent a river system or a highway system.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-multisurface"></a>11.4.2.12 MultiSurface Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">MultiSurface</code> is a geometry collection
          composed of surface elements. <code class="literal">MultiSurface</code>
          is a noninstantiable class. Its only instantiable subclass is
          <code class="literal">MultiPolygon</code>.
        </p><p>
          <span class="bold"><strong><code class="literal">MultiSurface</code>
          Assertions</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              Surfaces within a <code class="literal">MultiSurface</code> have no
              interiors that intersect.
            </p></li><li class="listitem"><p>
              Surfaces within a <code class="literal">MultiSurface</code> have
              boundaries that intersect at most at a finite number of
              points.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a name="gis-class-multipolygon"></a>11.4.2.13 MultiPolygon Class</h4>

</div>

</div>

</div>
<p>
          A <code class="literal">MultiPolygon</code> is a
          <code class="literal">MultiSurface</code> object composed of
          <code class="literal">Polygon</code> elements.
        </p><p>
          <span class="bold"><strong><code class="literal">MultiPolygon</code>
          Examples</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              On a region map, a <code class="literal">MultiPolygon</code> could
              represent a system of lakes.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">MultiPolygon</code>
          Assertions</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> has no two
              <code class="literal">Polygon</code> elements with interiors that
              intersect.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> has no two
              <code class="literal">Polygon</code> elements that cross (crossing
              is also forbidden by the previous assertion), or that
              touch at an infinite number of points.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> may not have cut lines,
              spikes, or punctures. A <code class="literal">MultiPolygon</code> is
              a regular, closed point set.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> that has more than one
              <code class="literal">Polygon</code> has an interior that is not
              connected. The number of connected components of the
              interior of a <code class="literal">MultiPolygon</code> is equal to
              the number of <code class="literal">Polygon</code> values in the
              <code class="literal">MultiPolygon</code>.
</p></li></ul>
</div>
<p>
          <span class="bold"><strong><code class="literal">MultiPolygon</code>
          Properties</strong></span>
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> is a two-dimensional
              geometry.
            </p></li><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> boundary is a set of
              closed curves (<code class="literal">LineString</code> values)
              corresponding to the boundaries of its
              <code class="literal">Polygon</code> elements.
            </p></li><li class="listitem"><p>
              Each <code class="literal">Curve</code> in the boundary of the
              <code class="literal">MultiPolygon</code> is in the boundary of
              exactly one <code class="literal">Polygon</code> element.
            </p></li><li class="listitem"><p>
              Every <code class="literal">Curve</code> in the boundary of an
              <code class="literal">Polygon</code> element is in the boundary of
              the <code class="literal">MultiPolygon</code>.
</p></li></ul>
</div>

</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="gis-data-formats"></a>11.4.3 Supported Spatial Data Formats</h3>

</div>

</div>

</div>
<p>
        Two standard spatial data formats are used to represent geometry
        objects in queries:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Well-Known Text (WKT) format
          </p></li><li class="listitem"><p>
            Well-Known Binary (WKB) format
</p></li></ul>
</div>
<p>
        Internally, MySQL stores geometry values in a format that is not
        identical to either WKT or WKB format. (Internal format is like
        WKB but with an initial 4 bytes to indicate the SRID.)
      </p><p>
        There are functions available to convert between different data
        formats; see <a class="xref" href="functions.html#gis-format-conversion-functions" title="12.16.6 Geometry Format Conversion Functions">Section 12.16.6, “Geometry Format Conversion Functions”</a>.
      </p><p>
        The following sections describe the spatial data formats MySQL
        uses:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><a class="xref" href="data-types.html#gis-wkt-format" title="Well-Known Text (WKT) Format">Well-Known Text (WKT) Format</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#gis-wkb-format" title="Well-Known Binary (WKB) Format">Well-Known Binary (WKB) Format</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#gis-internal-format" title="Internal Geometry Storage Format">Internal Geometry Storage Format</a></p></li></ul>
</div>

<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h4 class="title"><a name="gis-wkt-format"></a>Well-Known Text (WKT) Format</h4>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336081984"></a><a class="indexterm" name="idm46444336080528"></a><a class="indexterm" name="idm46444336079040"></a><p>
          The Well-Known Text (WKT) representation of geometry values is
          designed for exchanging geometry data in ASCII form. The
          OpenGIS specification provides a Backus-Naur grammar that
          specifies the formal production rules for writing WKT values
          (see <a class="xref" href="data-types.html#spatial-types" title="11.4 Spatial Data Types">Section 11.4, “Spatial Data Types”</a>).
        </p><p>
          Examples of WKT representations of geometry objects:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              A <code class="literal">Point</code>:
            </p><pre data-lang="simple" class="programlisting">POINT(15 20)</pre><p>
              The point coordinates are specified with no separating
              comma. This differs from the syntax for the SQL
              <a class="link" href="functions.html#function_point"><code class="literal">Point()</code></a> function, which
              requires a comma between the coordinates. Take care to use
              the syntax appropriate to the context of a given spatial
              operation. For example, the following statements both use
              <a class="link" href="functions.html#function_st-x"><code class="literal">ST_X()</code></a> to extract the
              X-coordinate from a <code class="literal">Point</code> object. The
              first produces the object directly using the
              <a class="link" href="functions.html#function_point"><code class="literal">Point()</code></a> function. The
              second uses a WKT representation converted to a
              <code class="literal">Point</code> with
              <a class="link" href="functions.html#function_st-geomfromtext"><code class="literal">ST_GeomFromText()</code></a>.
            </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT ST_X(Point(15, 20));</code></strong>
+---------------------+
| ST_X(POINT(15, 20)) |
+---------------------+
|                  15 |
+---------------------+

mysql&gt; <strong class="userinput"><code>SELECT ST_X(ST_GeomFromText('POINT(15 20)'));</code></strong>
+---------------------------------------+
| ST_X(ST_GeomFromText('POINT(15 20)')) |
+---------------------------------------+
|                                    15 |
+---------------------------------------+
</pre></li><li class="listitem"><p>
              A <code class="literal">LineString</code> with four points:
            </p><pre data-lang="simple" class="programlisting">LINESTRING(0 0, 10 10, 20 25, 50 60)</pre><p>
              The point coordinate pairs are separated by commas.
            </p></li><li class="listitem"><p>
              A <code class="literal">Polygon</code> with one exterior ring and
              one interior ring:
            </p><pre data-lang="simple" class="programlisting">POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))</pre></li><li class="listitem"><p>
              A <code class="literal">MultiPoint</code> with three
              <code class="literal">Point</code> values:
            </p><pre data-lang="simple" class="programlisting">MULTIPOINT(0 0, 20 20, 60 60)</pre><p>
              Spatial functions such as
              <a class="link" href="functions.html#function_st-mpointfromtext"><code class="literal">ST_MPointFromText()</code></a> and
              <a class="link" href="functions.html#function_st-geomfromtext"><code class="literal">ST_GeomFromText()</code></a> that
              accept WKT-format representations of
              <code class="literal">MultiPoint</code> values permit individual
              points within values to be surrounded by parentheses. For
              example, both of the following function calls are valid:
            </p><pre data-lang="sql" class="programlisting">ST_MPointFromText('MULTIPOINT (1 1, 2 2, 3 3)')
ST_MPointFromText('MULTIPOINT ((1 1), (2 2), (3 3))')</pre></li><li class="listitem"><p>
              A <code class="literal">MultiLineString</code> with two
              <code class="literal">LineString</code> values:
            </p><pre data-lang="simple" class="programlisting">MULTILINESTRING((10 10, 20 20), (15 15, 30 15))</pre></li><li class="listitem"><p>
              A <code class="literal">MultiPolygon</code> with two
              <code class="literal">Polygon</code> values:
            </p><pre data-lang="simple" class="programlisting">MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)),((5 5,7 5,7 7,5 7, 5 5)))</pre></li><li class="listitem"><p>
              A <code class="literal">GeometryCollection</code> consisting of two
              <code class="literal">Point</code> values and one
              <code class="literal">LineString</code>:
</p><pre data-lang="simple" class="programlisting">GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), LINESTRING(15 15, 20 20))</pre></li></ul>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="gis-wkb-format"></a>Well-Known Binary (WKB) Format</h4>

</div>

</div>

</div>
<a class="indexterm" name="idm46444336033760"></a><a class="indexterm" name="idm46444336032304"></a><a class="indexterm" name="idm46444336030800"></a><p>
          The Well-Known Binary (WKB) representation of geometric values
          is used for exchanging geometry data as binary streams
          represented by <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> values
          containing geometric WKB information. This format is defined
          by the OpenGIS specification (see
          <a class="xref" href="data-types.html#spatial-types" title="11.4 Spatial Data Types">Section 11.4, “Spatial Data Types”</a>). It is also defined in the
          ISO <em class="citetitle">SQL/MM Part 3: Spatial</em> standard.
        </p><p>
          WKB uses 1-byte unsigned integers, 4-byte unsigned integers,
          and 8-byte double-precision numbers (IEEE 754 format). A byte
          is eight bits.
        </p><p>
          For example, a WKB value that corresponds to <code class="literal">POINT(1
          -1)</code> consists of this sequence of 21 bytes, each
          represented by two hexadecimal digits:
        </p><pre data-lang="simple" class="programlisting">0101000000000000000000F03F000000000000F0BF</pre><p>
          The sequence consists of the components shown in the following
          table.
</p>
<div class="table">
<a name="wkb-components-example-table"></a><p class="title"><b>Table 11.2 WKB Components Example</b></p>
<div class="table-contents">
<table summary="Example showing component in WKB values."><col width="30%"><col width="30%"><col width="40%"><thead><tr>
              <th scope="col">Component</th>
              <th scope="col">Size</th>
              <th scope="col">Value</th>
            </tr></thead><tbody><tr>
              <td align="left" scope="row">Byte order</td>
              <td align="left">1 byte</td>
              <td align="left"><code class="literal">01</code></td>
            </tr><tr>
              <td align="left" scope="row">WKB type</td>
              <td align="left">4 bytes</td>
              <td align="left"><code class="literal">01000000</code></td>
            </tr><tr>
              <td align="left" scope="row">X coordinate</td>
              <td align="left">8 bytes</td>
              <td align="left"><code class="literal">000000000000F03F</code></td>
            </tr><tr>
              <td align="left" scope="row">Y coordinate</td>
              <td align="left">8 bytes</td>
              <td align="left"><code class="literal">000000000000F0BF</code></td>
</tr></tbody></table>
</div>

</div>
<br class="table-break"><p>
          Component representation is as follows:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              The byte order indicator is either 1 or 0 to signify
              little-endian or big-endian storage. The little-endian and
              big-endian byte orders are also known as Network Data
              Representation (NDR) and External Data Representation
              (XDR), respectively.
            </p></li><li class="listitem"><p>
              The WKB type is a code that indicates the geometry type.
              MySQL uses values from 1 through 7 to indicate
              <code class="literal">Point</code>, <code class="literal">LineString</code>,
              <code class="literal">Polygon</code>, <code class="literal">MultiPoint</code>,
              <code class="literal">MultiLineString</code>,
              <code class="literal">MultiPolygon</code>, and
              <code class="literal">GeometryCollection</code>.
            </p></li><li class="listitem"><p>
              A <code class="literal">Point</code> value has X and Y coordinates,
              each represented as a double-precision value.
</p></li></ul>
</div>
<p>
          WKB values for more complex geometry values have more complex
          data structures, as detailed in the OpenGIS specification.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h4 class="title"><a name="gis-internal-format"></a>Internal Geometry Storage Format</h4>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335985184"></a><a class="indexterm" name="idm46444335983728"></a><p>
          MySQL stores geometry values using 4 bytes to indicate the
          SRID followed by the WKB representation of the value. For a
          description of WKB format, see
          <a class="xref" href="data-types.html#gis-wkb-format" title="Well-Known Binary (WKB) Format">Well-Known Binary (WKB) Format</a>.
        </p><p>
          For the WKB part, these MySQL-specific considerations apply:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              The byte-order indicator byte is 1 because MySQL stores
              geometries as little-ending values.
            </p></li><li class="listitem"><p>
              MySQL supports geometry types of <code class="literal">Point</code>,
              <code class="literal">LineString</code>, <code class="literal">Polygon</code>,
              <code class="literal">MultiPoint</code>,
              <code class="literal">MultiLineString</code>,
              <code class="literal">MultiPolygon</code>, and
              <code class="literal">GeometryCollection</code>. Other geometry
              types are not supported.
            </p></li><li class="listitem"><p>
              Only <code class="literal">GeometryCollection</code> can be empty.
              Such a value is stored with 0 elements.
            </p></li><li class="listitem"><p>
              Polygon rings can be specified both clockwise and
              counterclockwise. MySQL flips the rings automatically when
              reading data.
</p></li></ul>
</div>
<p>
          Cartesian coordinates are stored in the length unit of the
          spatial reference system, with X values in the X coordinates
          and Y values in the Y coordinates. Axis directions are those
          specified by the spatial reference system.
        </p><p>
          Geographic coordinates are stored in the angle unit of the
          spatial reference system, with longitudes in the X coordinates
          and latitudes in the Y coordinates. Axis directions and the
          meridian are those specified by the spatial reference system.
        </p><p>
          The <a class="link" href="functions.html#function_length"><code class="literal">LENGTH()</code></a> function returns
          the space in bytes required for value storage. Example:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @g = ST_GeomFromText('POINT(1 -1)');</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT LENGTH(@g);</code></strong>
+------------+
| LENGTH(@g) |
+------------+
|         25 |
+------------+
mysql&gt; <strong class="userinput"><code>SELECT HEX(@g);</code></strong>
+----------------------------------------------------+
| HEX(@g)                                            |
+----------------------------------------------------+
| 000000000101000000000000000000F03F000000000000F0BF |
+----------------------------------------------------+
</pre><p>
          The value length is 25 bytes, made up of these components (as
          can be seen from the hexadecimal value):
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
              4 bytes for integer SRID (0)
            </p></li><li class="listitem"><p>
              1 byte for integer byte order (1 = little-endian)
            </p></li><li class="listitem"><p>
              4 bytes for integer type information (1 =
              <code class="literal">Point</code>)
            </p></li><li class="listitem"><p>
              8 bytes for double-precision X coordinate (1)
            </p></li><li class="listitem"><p>
              8 bytes for double-precision Y coordinate (−1)
</p></li></ul>
</div>

</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="geometry-well-formedness-validity"></a>11.4.4 Geometry Well-Formedness and Validity</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335956528"></a><a class="indexterm" name="idm46444335955024"></a><a class="indexterm" name="idm46444335953520"></a><a class="indexterm" name="idm46444335952032"></a><a class="indexterm" name="idm46444335950544"></a><a class="indexterm" name="idm46444335949056"></a><a class="indexterm" name="idm46444335947568"></a><a class="indexterm" name="idm46444335946080"></a><a class="indexterm" name="idm46444335944592"></a><a class="indexterm" name="idm46444335943088"></a><p>
        For geometry values, MySQL distinguishes between the concepts of
        syntactically well-formed and geometrically valid.
      </p><p>
        A geometry is syntactically well-formed if it satisfies
        conditions such as those in this (nonexhaustive) list:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Linestrings have at least two points
          </p></li><li class="listitem"><p>
            Polygons have at least one ring
          </p></li><li class="listitem"><p>
            Polygon rings are closed (first and last points the same)
          </p></li><li class="listitem"><p>
            Polygon rings have at least 4 points (minimum polygon is a
            triangle with first and last points the same)
          </p></li><li class="listitem"><p>
            Collections are not empty (except
            <code class="literal">GeometryCollection</code>)
</p></li></ul>
</div>
<p>
        A geometry is geometrically valid if it is syntactically
        well-formed and satisfies conditions such as those in this
        (nonexhaustive) list:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Polygons are not self-intersecting
          </p></li><li class="listitem"><p>
            Polygon interior rings are inside the exterior ring
          </p></li><li class="listitem"><p>
            Multipolygons do not have overlapping polygons
</p></li></ul>
</div>
<p>
        Spatial functions fail if a geometry is not syntactically
        well-formed. Spatial import functions that parse WKT or WKB
        values raise an error for attempts to create a geometry that is
        not syntactically well-formed. Syntactic well-formedness is also
        checked for attempts to store geometries into tables.
      </p><p>
        It is permitted to insert, select, and update geometrically
        invalid geometries, but they must be syntactically well-formed.
        Due to the computational expense, MySQL does not check
        explicitly for geometric validity. Spatial computations may
        detect some cases of invalid geometries and raise an error, but
        they may also return an undefined result without detecting the
        invalidity. Applications that require geometically valid
        geometries should check them using the
        <a class="link" href="functions.html#function_st-isvalid"><code class="literal">ST_IsValid()</code></a> function.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="spatial-reference-systems"></a>11.4.5 Spatial Reference System Support</h3>

</div>

</div>

</div>
<p>
        A spatial reference system (SRS) for spatial data is a
        coordinate-based system for geographic locations.
      </p><p>
        There are different types of spatial reference systems:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            A projected SRS is a projection of a globe onto a flat
            surface; that is, a flat map. For example, a light bulb
            inside a globe that shines on a paper cylinder surrounding
            the globe projects a map onto the paper. The result is
            georeferenced: Each point maps to a place on the globe. The
            coordinate system on that plane is Cartesian using a length
            unit (meters, feet, and so forth), rather than degrees of
            longitude and latitude.
          </p><p>
            The globes in this case are ellipsoids; that is, flattened
            spheres. Earth is a bit shorter in its North-South axis than
            its East-West axis, so a slightly flattened sphere is more
            correct, but perfect spheres permit faster calculations.
          </p></li><li class="listitem"><p>
            A geographic SRS is a nonprojected SRS representing
            longitude-latitude (or latitude-longitude) coordinates on an
            ellipsoid, in any angular unit.
          </p></li><li class="listitem"><p>
            The SRS denoted in MySQL by SRID 0 represents an infinite
            flat Cartesian plane with no units assigned to its axes.
            Unlike projected SRSs, it is not georeferenced and it does
            not necessarily represent Earth. It is an abstract plane
            that can be used for anything. SRID 0 is the default SRID
            for spatial data in MySQL.
</p></li></ul>
</div>
<p>
        MySQL maintains information about available spatial reference
        systems for spatial data in the data dictionary
        <code class="literal">mysql.st_spatial_reference_systems</code> table,
        which can store entries for projected and geographic SRSs. This
        data dictionary table is invisible, but SRS entry contents are
        available through the <code class="literal">INFORMATION_SCHEMA</code>
        <a class="link" href="information-schema.html#st-spatial-reference-systems-table" title="25.34 The INFORMATION_SCHEMA ST_SPATIAL_REFERENCE_SYSTEMS Table"><code class="literal">ST_SPATIAL_REFERENCE_SYSTEMS</code></a> table,
        implemented as a view on
        <code class="literal">mysql.st_spatial_reference_systems</code> (see
        <a class="xref" href="information-schema.html#st-spatial-reference-systems-table" title="25.34 The INFORMATION_SCHEMA ST_SPATIAL_REFERENCE_SYSTEMS Table">Section 25.34, “The INFORMATION_SCHEMA ST_SPATIAL_REFERENCE_SYSTEMS Table”</a>).
      </p><p>
        The following example shows what an SRS entry looks like:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT *</code></strong>
       <strong class="userinput"><code>FROM INFORMATION_SCHEMA.ST_SPATIAL_REFERENCE_SYSTEMS</code></strong>
       <strong class="userinput"><code>WHERE SRS_ID = 4326\G</code></strong>
*************************** 1. row ***************************
                SRS_NAME: WGS 84
                  SRS_ID: 4326
            ORGANIZATION: EPSG
ORGANIZATION_COORDSYS_ID: 4326
              DEFINITION: GEOGCS["WGS 84",DATUM["World Geodetic System 1984",
                          SPHEROID["WGS 84",6378137,298.257223563,
                          AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],
                          PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],
                          UNIT["degree",0.017453292519943278,
                          AUTHORITY["EPSG","9122"]],
                          AXIS["Lat",NORTH],AXIS["Long",EAST],
                          AUTHORITY["EPSG","4326"]]
             DESCRIPTION:
</pre><p>
        This entry describes the SRS used for GPS systems. It has a name
        (<code class="literal">SRS_NAME</code>) of WGS 84 and an ID
        (<code class="literal">SRS_ID</code>) of 4326, which is the ID used by the
        <a class="ulink" href="http://epsg.org" target="_top">European Petroleum Survey
        Group</a> (EPSG).
      </p><p>
        SRS definitions in the <code class="literal">DEFINITION</code> column are
        WKT values, represented as specified in the
        <a class="ulink" href="http://www.opengeospatial.org" target="_top">Open Geospatial
        Consortium</a> document
        <a class="ulink" href="http://docs.opengeospatial.org/is/12-063r5/12-063r5.html" target="_top">OGC
        12-063r5</a>.
      </p><p>
        <code class="literal">SRS_ID</code> values represent the same kind of
        values passed as the SRID argument to spatial functions. SRID 0
        (the unitless Cartesian plane) is special. It is always a legal
        spatial reference system ID and can be used in any computations
        on spatial data that depend on SRID values.
      </p><p>
        For computations on multiple geometry values, all values must
        have the same SRID or an error occurs.
      </p><p>
        SRS definition parsing occurs on demand when definitions are
        needed by GIS functions. Parsed definitions are cached in the
        data dictionary cache so that parsing overhead is not incurred
        for every statement that needs SRS information.
      </p><p>
        To enable manipulation of SRS entries stored in the data
        dictionary, MySQL provides these SQL statements:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <a class="link" href="sql-statements.html#create-spatial-reference-system" title="13.1.19 CREATE SPATIAL REFERENCE SYSTEM Statement"><code class="literal">CREATE SPATIAL REFERENCE
            SYSTEM</code></a>: See
            <a class="xref" href="sql-statements.html#create-spatial-reference-system" title="13.1.19 CREATE SPATIAL REFERENCE SYSTEM Statement">Section 13.1.19, “CREATE SPATIAL REFERENCE SYSTEM Statement”</a>. The
            description for this statement includes additional
            information about SRS components.
          </p></li><li class="listitem"><p>
            <a class="link" href="sql-statements.html#drop-spatial-reference-system" title="13.1.31 DROP SPATIAL REFERENCE SYSTEM Statement"><code class="literal">DROP SPATIAL REFERENCE
            SYSTEM</code></a>: See
            <a class="xref" href="sql-statements.html#drop-spatial-reference-system" title="13.1.31 DROP SPATIAL REFERENCE SYSTEM Statement">Section 13.1.31, “DROP SPATIAL REFERENCE SYSTEM Statement”</a>.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="creating-spatial-columns"></a>11.4.6 Creating Spatial Columns</h3>

</div>

</div>

</div>
<p>
        MySQL provides a standard way of creating spatial columns for
        geometry types, for example, with <a class="link" href="sql-statements.html#create-table" title="13.1.20 CREATE TABLE Statement"><code class="literal">CREATE
        TABLE</code></a> or <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>.
        Spatial columns are supported for
        <a class="link" href="storage-engines.html#myisam-storage-engine" title="16.2 The MyISAM Storage Engine"><code class="literal">MyISAM</code></a>,
        <a class="link" href="innodb-storage-engine.html" title="Chapter 15 The InnoDB Storage Engine"><code class="literal">InnoDB</code></a>,
        <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a>, and
        <a class="link" href="storage-engines.html#archive-storage-engine" title="16.5 The ARCHIVE Storage Engine"><code class="literal">ARCHIVE</code></a> tables. See also the notes
        about spatial indexes under
        <a class="xref" href="data-types.html#creating-spatial-indexes" title="11.4.10 Creating Spatial Indexes">Section 11.4.10, “Creating Spatial Indexes”</a>.
      </p><p>
        Columns with a spatial data type can have an SRID attribute, to
        explicitly indicate the spatial reference system (SRS) for
        values stored in the column. For implications of an
        SRID-restricted column, see
        <a class="xref" href="data-types.html#spatial-type-overview" title="11.4.1 Spatial Data Types">Section 11.4.1, “Spatial Data Types”</a>.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Use the <a class="link" href="sql-statements.html#create-table" title="13.1.20 CREATE TABLE Statement"><code class="literal">CREATE TABLE</code></a>
            statement to create a table with a spatial column:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY);</pre></li><li class="listitem"><p>
            Use the <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a> statement
            to add or drop a spatial column to or from an existing
            table:
          </p><pre data-lang="sql" class="programlisting">ALTER TABLE geom ADD pt POINT;
ALTER TABLE geom DROP pt;</pre></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="populating-spatial-columns"></a>11.4.7 Populating Spatial Columns</h3>

</div>

</div>

</div>
<p>
        After you have created spatial columns, you can populate them
        with spatial data.
      </p><p>
        Values should be stored in internal geometry format, but you can
        convert them to that format from either Well-Known Text (WKT) or
        Well-Known Binary (WKB) format. The following examples
        demonstrate how to insert geometry values into a table by
        converting WKT values to internal geometry format:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Perform the conversion directly in the
            <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a> statement:
          </p><pre data-lang="sql" class="programlisting">INSERT INTO geom VALUES (ST_GeomFromText('POINT(1 1)'));

SET @g = 'POINT(1 1)';
INSERT INTO geom VALUES (ST_GeomFromText(@g));</pre></li><li class="listitem"><p>
            Perform the conversion prior to the
            <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a>:
          </p><pre data-lang="sql" class="programlisting">SET @g = ST_GeomFromText('POINT(1 1)');
INSERT INTO geom VALUES (@g);</pre></li></ul>
</div>
<p>
        The following examples insert more complex geometries into the
        table:
      </p><pre data-lang="sql" class="programlisting">SET @g = 'LINESTRING(0 0,1 1,2 2)';
INSERT INTO geom VALUES (ST_GeomFromText(@g));

SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
INSERT INTO geom VALUES (ST_GeomFromText(@g));

SET @g =
'GEOMETRYCOLLECTION(POINT(1 1),LINESTRING(0 0,1 1,2 2,3 3,4 4))';
INSERT INTO geom VALUES (ST_GeomFromText(@g));</pre><p>
        The preceding examples use
        <a class="link" href="functions.html#function_st-geomfromtext"><code class="literal">ST_GeomFromText()</code></a> to create
        geometry values. You can also use type-specific functions:
      </p><pre data-lang="sql" class="programlisting">SET @g = 'POINT(1 1)';
INSERT INTO geom VALUES (ST_PointFromText(@g));

SET @g = 'LINESTRING(0 0,1 1,2 2)';
INSERT INTO geom VALUES (ST_LineStringFromText(@g));

SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
INSERT INTO geom VALUES (ST_PolygonFromText(@g));

SET @g =
'GEOMETRYCOLLECTION(POINT(1 1),LINESTRING(0 0,1 1,2 2,3 3,4 4))';
INSERT INTO geom VALUES (ST_GeomCollFromText(@g));</pre><p>
        A client application program that wants to use WKB
        representations of geometry values is responsible for sending
        correctly formed WKB in queries to the server. There are several
        ways to satisfy this requirement. For example:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Inserting a <code class="literal">POINT(1 1)</code> value with hex
            literal syntax:
          </p><pre data-lang="sql" class="programlisting">INSERT INTO geom VALUES
(ST_GeomFromWKB(X'0101000000000000000000F03F000000000000F03F'));</pre></li><li class="listitem"><p>
            An ODBC application can send a WKB representation, binding
            it to a placeholder using an argument of
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> type:
          </p><pre data-lang="sql" class="programlisting">INSERT INTO geom VALUES (ST_GeomFromWKB(?))</pre><p>
            Other programming interfaces may support a similar
            placeholder mechanism.
          </p></li><li class="listitem"><p>
            In a C program, you can escape a binary value using
            <a class="link" href="connectors-apis.html#mysql-real-escape-string-quote" title="28.7.6.56 mysql_real_escape_string_quote()"><code class="literal">mysql_real_escape_string_quote()</code></a>
            and include the result in a query string that is sent to the
            server. See
            <a class="xref" href="connectors-apis.html#mysql-real-escape-string-quote" title="28.7.6.56 mysql_real_escape_string_quote()">Section 28.7.6.56, “mysql_real_escape_string_quote()”</a>.
</p></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="fetching-spatial-data"></a>11.4.8 Fetching Spatial Data</h3>

</div>

</div>

</div>
<p>
        Geometry values stored in a table can be fetched in internal
        format. You can also convert them to WKT or WKB format.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Fetching spatial data in internal format:
          </p><p>
            Fetching geometry values using internal format can be useful
            in table-to-table transfers:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom2 (g GEOMETRY) SELECT g FROM geom;</pre></li><li class="listitem"><p>
            Fetching spatial data in WKT format:
          </p><p>
            The <a class="link" href="functions.html#function_st-astext"><code class="literal">ST_AsText()</code></a> function
            converts a geometry from internal format to a WKT string.
          </p><pre data-lang="sql" class="programlisting">SELECT ST_AsText(g) FROM geom;</pre></li><li class="listitem"><p>
            Fetching spatial data in WKB format:
          </p><p>
            The <a class="link" href="functions.html#function_st-asbinary"><code class="literal">ST_AsBinary()</code></a> function
            converts a geometry from internal format to a
            <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> containing the WKB
            value.
</p><pre data-lang="sql" class="programlisting">SELECT ST_AsBinary(g) FROM geom;</pre></li></ul>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="optimizing-spatial-analysis"></a>11.4.9 Optimizing Spatial Analysis</h3>

</div>

</div>

</div>
<p>
        For <a class="link" href="storage-engines.html#myisam-storage-engine" title="16.2 The MyISAM Storage Engine"><code class="literal">MyISAM</code></a> and
        <code class="literal">InnoDB</code> tables, search operations in columns
        containing spatial data can be optimized using
        <code class="literal">SPATIAL</code> indexes. The most typical operations
        are:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Point queries that search for all objects that contain a
            given point
          </p></li><li class="listitem"><p>
            Region queries that search for all objects that overlap a
            given region
</p></li></ul>
</div>
<p>
        MySQL uses <span class="bold"><strong>R-Trees with quadratic
        splitting</strong></span> for <code class="literal">SPATIAL</code> indexes on
        spatial columns. A <code class="literal">SPATIAL</code> index is built
        using the minimum bounding rectangle (MBR) of a geometry. For
        most geometries, the MBR is a minimum rectangle that surrounds
        the geometries. For a horizontal or a vertical linestring, the
        MBR is a rectangle degenerated into the linestring. For a point,
        the MBR is a rectangle degenerated into the point.
      </p><p>
        It is also possible to create normal indexes on spatial columns.
        In a non-<code class="literal">SPATIAL</code> index, you must declare a
        prefix for any spatial column except for
        <code class="literal">POINT</code> columns.
      </p><p>
        <code class="literal">MyISAM</code> and <code class="literal">InnoDB</code> support
        both <code class="literal">SPATIAL</code> and
        non-<code class="literal">SPATIAL</code> indexes. Other storage engines
        support non-<code class="literal">SPATIAL</code> indexes, as described in
        <a class="xref" href="sql-statements.html#create-index" title="13.1.15 CREATE INDEX Statement">Section 13.1.15, “CREATE INDEX Statement”</a>.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="creating-spatial-indexes"></a>11.4.10 Creating Spatial Indexes</h3>

</div>

</div>

</div>
<p>
        For <code class="literal">InnoDB</code> and <code class="literal">MyISAM</code>
        tables, MySQL can create spatial indexes using syntax similar to
        that for creating regular indexes, but using the
        <code class="literal">SPATIAL</code> keyword. Columns in spatial indexes
        must be declared <code class="literal">NOT NULL</code>. The following
        examples demonstrate how to create spatial indexes:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            With <a class="link" href="sql-statements.html#create-table" title="13.1.20 CREATE TABLE Statement"><code class="literal">CREATE TABLE</code></a>:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326, SPATIAL INDEX(g));</pre></li><li class="listitem"><p>
            With <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326);
ALTER TABLE geom ADD SPATIAL INDEX(g);</pre></li><li class="listitem"><p>
            With <a class="link" href="sql-statements.html#create-index" title="13.1.15 CREATE INDEX Statement"><code class="literal">CREATE INDEX</code></a>:
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326);
CREATE SPATIAL INDEX g ON geom (g);</pre></li></ul>
</div>
<p>
        <code class="literal">SPATIAL INDEX</code> creates an R-tree index. For
        storage engines that support nonspatial indexing of spatial
        columns, the engine creates a B-tree index. A B-tree index on
        spatial values is useful for exact-value lookups, but not for
        range scans.
      </p><p>
        The optimizer can use spatial indexes defined on columns that
        are SRID-restricted. For more information, see
        <a class="xref" href="data-types.html#spatial-type-overview" title="11.4.1 Spatial Data Types">Section 11.4.1, “Spatial Data Types”</a>, and
        <a class="xref" href="optimization.html#spatial-index-optimization" title="8.3.3 SPATIAL Index Optimization">Section 8.3.3, “SPATIAL Index Optimization”</a>.
      </p><p>
        For more information on indexing spatial columns, see
        <a class="xref" href="sql-statements.html#create-index" title="13.1.15 CREATE INDEX Statement">Section 13.1.15, “CREATE INDEX Statement”</a>.
      </p><p>
        To drop spatial indexes, use <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER
        TABLE</code></a> or <a class="link" href="sql-statements.html#drop-index" title="13.1.27 DROP INDEX Statement"><code class="literal">DROP INDEX</code></a>:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            With <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>:
          </p><pre data-lang="sql" class="programlisting">ALTER TABLE geom DROP INDEX g;</pre></li><li class="listitem"><p>
            With <a class="link" href="sql-statements.html#drop-index" title="13.1.27 DROP INDEX Statement"><code class="literal">DROP INDEX</code></a>:
</p><pre data-lang="sql" class="programlisting">DROP INDEX g ON geom;</pre></li></ul>
</div>
<p>
        Example: Suppose that a table <code class="literal">geom</code> contains
        more than 32,000 geometries, which are stored in the column
        <code class="literal">g</code> of type <code class="literal">GEOMETRY</code>. The
        table also has an <code class="literal">AUTO_INCREMENT</code> column
        <code class="literal">fid</code> for storing object ID values.
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>DESCRIBE geom;</code></strong>
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| fid   | int(11)  |      | PRI | NULL    | auto_increment |
| g     | geometry |      |     |         |                |
+-------+----------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT COUNT(*) FROM geom;</code></strong>
+----------+
| count(*) |
+----------+
|    32376 |
+----------+
1 row in set (0.00 sec)
</pre><p>
        To add a spatial index on the column <code class="literal">g</code>, use
        this statement:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>ALTER TABLE geom ADD SPATIAL INDEX(g);</code></strong>
Query OK, 32376 rows affected (4.05 sec)
Records: 32376  Duplicates: 0  Warnings: 0
</pre>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a name="using-spatial-indexes"></a>11.4.11 Using Spatial Indexes</h3>

</div>

</div>

</div>
<p>
        The optimizer investigates whether available spatial indexes can
        be involved in the search for queries that use a function such
        as <a class="link" href="functions.html#function_mbrcontains"><code class="literal">MBRContains()</code></a> or
        <a class="link" href="functions.html#function_mbrwithin"><code class="literal">MBRWithin()</code></a> in the
        <code class="literal">WHERE</code> clause. The following query finds all
        objects that are in the given rectangle:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @poly =</code></strong>
    -&gt; <strong class="userinput"><code>'Polygon((30000 15000,
                 31000 15000,
                 31000 16000,
                 30000 16000,
                 30000 15000))';</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT fid,ST_AsText(g) FROM geom WHERE</code></strong>
    -&gt; <strong class="userinput"><code>MBRContains(ST_GeomFromText(@poly),g);</code></strong>
+-----+---------------------------------------------------------------+
| fid | ST_AsText(g)                                                  |
+-----+---------------------------------------------------------------+
|  21 | LINESTRING(30350.4 15828.8,30350.6 15845,30333.8 15845,30 ... |
|  22 | LINESTRING(30350.6 15871.4,30350.6 15887.8,30334 15887.8, ... |
|  23 | LINESTRING(30350.6 15914.2,30350.6 15930.4,30334 15930.4, ... |
|  24 | LINESTRING(30290.2 15823,30290.2 15839.4,30273.4 15839.4, ... |
|  25 | LINESTRING(30291.4 15866.2,30291.6 15882.4,30274.8 15882. ... |
|  26 | LINESTRING(30291.6 15918.2,30291.6 15934.4,30275 15934.4, ... |
| 249 | LINESTRING(30337.8 15938.6,30337.8 15946.8,30320.4 15946. ... |
|   1 | LINESTRING(30250.4 15129.2,30248.8 15138.4,30238.2 15136. ... |
|   2 | LINESTRING(30220.2 15122.8,30217.2 15137.8,30207.6 15136, ... |
|   3 | LINESTRING(30179 15114.4,30176.6 15129.4,30167 15128,3016 ... |
|   4 | LINESTRING(30155.2 15121.4,30140.4 15118.6,30142 15109,30 ... |
|   5 | LINESTRING(30192.4 15085,30177.6 15082.2,30179.2 15072.4, ... |
|   6 | LINESTRING(30244 15087,30229 15086.2,30229.4 15076.4,3024 ... |
|   7 | LINESTRING(30200.6 15059.4,30185.6 15058.6,30186 15048.8, ... |
|  10 | LINESTRING(30179.6 15017.8,30181 15002.8,30190.8 15003.6, ... |
|  11 | LINESTRING(30154.2 15000.4,30168.6 15004.8,30166 15014.2, ... |
|  13 | LINESTRING(30105 15065.8,30108.4 15050.8,30118 15053,3011 ... |
| 154 | LINESTRING(30276.2 15143.8,30261.4 15141,30263 15131.4,30 ... |
| 155 | LINESTRING(30269.8 15084,30269.4 15093.4,30258.6 15093,30 ... |
| 157 | LINESTRING(30128.2 15011,30113.2 15010.2,30113.6 15000.4, ... |
+-----+---------------------------------------------------------------+
20 rows in set (0.00 sec)
</pre><p>
        Use <a class="link" href="sql-statements.html#explain" title="13.8.2 EXPLAIN Statement"><code class="literal">EXPLAIN</code></a> to check the way this
        query is executed:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @poly =</code></strong>
    -&gt; <strong class="userinput"><code>'Polygon((30000 15000,
                 31000 15000,
                 31000 16000,
                 30000 16000,
                 30000 15000))';</code></strong>
mysql&gt; <strong class="userinput"><code>EXPLAIN SELECT fid,ST_AsText(g) FROM geom WHERE</code></strong>
    -&gt; <strong class="userinput"><code>MBRContains(ST_GeomFromText(@poly),g)\G</code></strong>
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: geom
         type: range
possible_keys: g
          key: g
      key_len: 32
          ref: NULL
         rows: 50
        Extra: Using where
1 row in set (0.00 sec)
</pre><p>
        Check what would happen without a spatial index:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @poly =</code></strong>
    -&gt; <strong class="userinput"><code>'Polygon((30000 15000,
                 31000 15000,
                 31000 16000,
                 30000 16000,
                 30000 15000))';</code></strong>
mysql&gt; <strong class="userinput"><code>EXPLAIN SELECT fid,ST_AsText(g) FROM g IGNORE INDEX (g) WHERE</code></strong>
    -&gt; <strong class="userinput"><code>MBRContains(ST_GeomFromText(@poly),g)\G</code></strong>
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: geom
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 32376
        Extra: Using where
1 row in set (0.00 sec)
</pre><p>
        Executing the <a class="link" href="sql-statements.html#select" title="13.2.10 SELECT Statement"><code class="literal">SELECT</code></a> statement
        without the spatial index yields the same result but causes the
        execution time to rise from 0.00 seconds to 0.46 seconds:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @poly =</code></strong>
    -&gt; <strong class="userinput"><code>'Polygon((30000 15000,
                 31000 15000,
                 31000 16000,
                 30000 16000,
                 30000 15000))';</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT fid,ST_AsText(g) FROM geom IGNORE INDEX (g) WHERE</code></strong>
    -&gt; <strong class="userinput"><code>MBRContains(ST_GeomFromText(@poly),g);</code></strong>
+-----+---------------------------------------------------------------+
| fid | ST_AsText(g)                                                  |
+-----+---------------------------------------------------------------+
|   1 | LINESTRING(30250.4 15129.2,30248.8 15138.4,30238.2 15136. ... |
|   2 | LINESTRING(30220.2 15122.8,30217.2 15137.8,30207.6 15136, ... |
|   3 | LINESTRING(30179 15114.4,30176.6 15129.4,30167 15128,3016 ... |
|   4 | LINESTRING(30155.2 15121.4,30140.4 15118.6,30142 15109,30 ... |
|   5 | LINESTRING(30192.4 15085,30177.6 15082.2,30179.2 15072.4, ... |
|   6 | LINESTRING(30244 15087,30229 15086.2,30229.4 15076.4,3024 ... |
|   7 | LINESTRING(30200.6 15059.4,30185.6 15058.6,30186 15048.8, ... |
|  10 | LINESTRING(30179.6 15017.8,30181 15002.8,30190.8 15003.6, ... |
|  11 | LINESTRING(30154.2 15000.4,30168.6 15004.8,30166 15014.2, ... |
|  13 | LINESTRING(30105 15065.8,30108.4 15050.8,30118 15053,3011 ... |
|  21 | LINESTRING(30350.4 15828.8,30350.6 15845,30333.8 15845,30 ... |
|  22 | LINESTRING(30350.6 15871.4,30350.6 15887.8,30334 15887.8, ... |
|  23 | LINESTRING(30350.6 15914.2,30350.6 15930.4,30334 15930.4, ... |
|  24 | LINESTRING(30290.2 15823,30290.2 15839.4,30273.4 15839.4, ... |
|  25 | LINESTRING(30291.4 15866.2,30291.6 15882.4,30274.8 15882. ... |
|  26 | LINESTRING(30291.6 15918.2,30291.6 15934.4,30275 15934.4, ... |
| 154 | LINESTRING(30276.2 15143.8,30261.4 15141,30263 15131.4,30 ... |
| 155 | LINESTRING(30269.8 15084,30269.4 15093.4,30258.6 15093,30 ... |
| 157 | LINESTRING(30128.2 15011,30113.2 15010.2,30113.6 15000.4, ... |
| 249 | LINESTRING(30337.8 15938.6,30337.8 15946.8,30320.4 15946. ... |
+-----+---------------------------------------------------------------+
20 rows in set (0.46 sec)
</pre>
</div>

</div>

<div class="section">

<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="json"></a>11.5 The JSON Data Type</h2>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335751616"></a>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><a class="xref" href="data-types.html#json-values" title="Creating JSON Values">Creating JSON Values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-normalization" title="Normalization, Merging, and Autowrapping of JSON Values">Normalization, Merging, and Autowrapping of JSON Values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-paths" title="Searching and Modifying JSON Values">Searching and Modifying JSON Values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-path-syntax" title="JSON Path Syntax">JSON Path Syntax</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-comparison" title="Comparison and Ordering of JSON Values">Comparison and Ordering of JSON Values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-converting-between-types" title="Converting between JSON and non-JSON values">Converting between JSON and non-JSON values</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#json-aggregation" title="Aggregation of JSON Values">Aggregation of JSON Values</a></p></li></ul>
</div>
<p>
      MySQL supports a native <code class="literal">JSON</code> data type defined
      by <a class="ulink" href="https://tools.ietf.org/html/rfc7159" target="_top">RFC
      7159</a> that enables efficient access to data in JSON
      (JavaScript Object Notation) documents. The
      <code class="literal">JSON</code> data type provides these advantages over
      storing JSON-format strings in a string column:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          Automatic validation of JSON documents stored in
          <code class="literal">JSON</code> columns. Invalid documents produce an
          error.
        </p></li><li class="listitem"><p>
          Optimized storage format. JSON documents stored in
          <code class="literal">JSON</code> columns are converted to an internal
          format that permits quick read access to document elements.
          When the server later must read a JSON value stored in this
          binary format, the value need not be parsed from a text
          representation. The binary format is structured to enable the
          server to look up subobjects or nested values directly by key
          or array index without reading all values before or after them
          in the document.
</p></li></ul>
</div>
<p>
      MySQL 8.0 also supports the <span class="emphasis"><em>JSON Merge
      Patch</em></span> format defined in
      <a class="ulink" href="https://tools.ietf.org/html/rfc7396" target="_top">RFC 7396</a>,
      using the <a class="link" href="functions.html#function_json-merge-patch"><code class="literal">JSON_MERGE_PATCH()</code></a>
      function. See the description of this function, as well as
      <a class="xref" href="data-types.html#json-normalization" title="Normalization, Merging, and Autowrapping of JSON Values">Normalization, Merging, and Autowrapping of JSON Values</a>, for examples and further
      information.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
        This discussion uses <code class="literal">JSON</code> in monotype to
        indicate specifically the JSON data type and <span class="quote">“<span class="quote">JSON</span>”</span>
        in regular font to indicate JSON data in general.
</p>
</div>
<p>
      The space required to store a <code class="literal">JSON</code> document is
      roughly the same as for <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGBLOB</code></a> or
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGTEXT</code></a>; see
      <a class="xref" href="data-types.html#storage-requirements" title="11.7 Data Type Storage Requirements">Section 11.7, “Data Type Storage Requirements”</a>, for more information. It
      is important to keep in mind that the size of any JSON document
      stored in a <code class="literal">JSON</code> column is limited to the value
      of the <a class="link" href="server-administration.html#sysvar_max_allowed_packet"><code class="literal">max_allowed_packet</code></a> system
      variable. (When the server is manipulating a JSON value internally
      in memory, it can be larger than this; the limit applies when the
      server stores it.) You can obtain the amount of space required to
      store a JSON document using the
      <a class="link" href="functions.html#function_json-storage-size"><code class="literal">JSON_STORAGE_SIZE()</code></a> function; note
      that for a <a class="link" href="data-types.html#json" title="11.5 The JSON Data Type"><code class="literal">JSON</code></a> column, the storage
      size—and thus the value returned by this function—is
      that used by the column prior to any partial updates that may have
      been performed on it (see the discussion of the JSON partial
      update optimization later in this section).
    </p><p>
      Prior to MySQL 8.0.13, a <code class="literal">JSON</code> column cannot
      have a non-<code class="literal">NULL</code> default value.
    </p><p>
      Along with the <code class="literal">JSON</code> data type, a set of SQL
      functions is available to enable operations on JSON values, such
      as creation, manipulation, and searching. The following discussion
      shows examples of these operations. For details about individual
      functions, see <a class="xref" href="functions.html#json-functions" title="12.17 JSON Functions">Section 12.17, “JSON Functions”</a>.
    </p><p>
      A set of spatial functions for operating on GeoJSON values is also
      available. See <a class="xref" href="functions.html#spatial-geojson-functions" title="12.16.11 Spatial GeoJSON Functions">Section 12.16.11, “Spatial GeoJSON Functions”</a>.
    </p><p>
      <code class="literal">JSON</code> columns, like columns of other binary
      types, are not indexed directly; instead, you can create an index
      on a generated column that extracts a scalar value from the
      <code class="literal">JSON</code> column. See
      <a class="xref" href="sql-statements.html#json-column-indirect-index" title="Indexing a Generated Column to Provide a JSON Column Index">Indexing a Generated Column to Provide a JSON Column Index</a>, for a detailed
      example.
    </p><p>
      The MySQL optimizer also looks for compatible indexes on virtual
      columns that match JSON expressions.
    </p><p>
      In MySQL 8.0.17 and later, the <a class="link" href="innodb-storage-engine.html" title="Chapter 15 The InnoDB Storage Engine"><code class="literal">InnoDB</code></a>
      storage engine supports multi-valued indexes on JSON arrays. See
      <a class="xref" href="sql-statements.html#create-index-multi-valued" title="Multi-Valued Indexes">Multi-Valued Indexes</a>.
    </p><p>
      MySQL NDB Cluster 8.0 supports <code class="literal">JSON</code> columns and
      MySQL JSON functions, including creation of an index on a column
      generated from a <code class="literal">JSON</code> column as a workaround
      for being unable to index a <code class="literal">JSON</code> column. A
      maximum of 3 <code class="literal">JSON</code> columns per
      <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> table is supported.
</p>
<h3><a name="json-partial-updates"></a>Partial Updates of JSON Values</h3>
<p>
      In MySQL 8.0, the optimizer can perform a partial,
      in-place update of a <code class="literal">JSON</code> column instead of
      removing the old document and writing the new document in its
      entirety to the column. This optimization can be performed for an
      update that meets the following conditions:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
          The column being updated was declared as
          <code class="literal">JSON</code>.
        </p></li><li class="listitem"><p>
          The <a class="link" href="sql-statements.html#update" title="13.2.13 UPDATE Statement"><code class="literal">UPDATE</code></a> statement uses any
          of the three functions
          <a class="link" href="functions.html#function_json-set"><code class="literal">JSON_SET()</code></a>,
          <a class="link" href="functions.html#function_json-replace"><code class="literal">JSON_REPLACE()</code></a>, or
          <a class="link" href="functions.html#function_json-remove"><code class="literal">JSON_REMOVE()</code></a> to update the
          column. A direct assignment of the column value (for example,
          <code class="literal">UPDATE mytable SET jcol = '{"a": 10, "b":
          25}'</code>) cannot be performed as a partial update.
        </p><p>
          Updates of multiple <code class="literal">JSON</code> columns in a
          single <code class="literal">UPDATE</code> statement can be optimized in
          this fashion; MySQL can perform partial updates of only those
          columns whose values are updated using the three functions
          just listed.
        </p></li><li class="listitem"><p>
          The input column and the target column must be the same
          column; a statement such as <code class="literal">UPDATE mytable SET jcol1
          = JSON_SET(jcol2, '$.a', 100)</code> cannot be performed as
          a partial update.
        </p><p>
          The update can use nested calls to any of the functions listed
          in the previous item, in any combination, as long as the input
          and target columns are the same.
        </p></li><li class="listitem"><p>
          All changes replace existing array or object values with new
          ones, and do not add any new elements to the parent object or
          array.
        </p></li><li class="listitem"><p>
          The value being replaced must be at least as large as the
          replacement value. In other words, the new value cannot be any
          larger than the old one.
        </p><p>
          A possible exception to this requirement occurs when a
          previous partial update has left sufficient space for the
          larger value. You can use the function
          <a class="link" href="functions.html#function_json-storage-free"><code class="literal">JSON_STORAGE_FREE()</code></a> see how
          much space has been freed by any partial updates of a
          <code class="literal">JSON</code> column.
</p></li></ul>
</div>
<p>
      Such partial updates can be written to the binary log using a
      compact format that saves space; this can be enabled by setting
      the <a class="link" href="replication.html#sysvar_binlog_row_value_options"><code class="literal">binlog_row_value_options</code></a>
      system variable to <code class="literal">PARTIAL_JSON</code>. See the
      description of this variable for more information.
    </p><p>
      The next few sections provide basic information regarding the
      creation and manipulation of JSON values.
</p>
<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h3 class="title"><a name="json-values"></a>Creating JSON Values</h3>
</div>
</div>
</div>
<a class="indexterm" name="idm46444335680880"></a><a class="indexterm" name="idm46444335679392"></a><a class="indexterm" name="idm46444335677904"></a><a class="indexterm" name="idm46444335676416"></a><a class="indexterm" name="idm46444335674928"></a><a class="indexterm" name="idm46444335673440"></a><a class="indexterm" name="idm46444335671952"></a><a class="indexterm" name="idm46444335670464"></a><a class="indexterm" name="idm46444335668976"></a><a class="indexterm" name="idm46444335667488"></a><a class="indexterm" name="idm46444335666000"></a><a class="indexterm" name="idm46444335664512"></a><a class="indexterm" name="idm46444335663024"></a><a class="indexterm" name="idm46444335661536"></a><a class="indexterm" name="idm46444335660048"></a><a class="indexterm" name="idm46444335658560"></a><p>
        A JSON array contains a list of values separated by commas and
        enclosed within <code class="literal">[</code> and <code class="literal">]</code>
        characters:
      </p><pre data-lang="json" class="programlisting">["abc", 10, null, true, false]</pre><p>
        A JSON object contains a set of key-value pairs separated by
        commas and enclosed within <code class="literal">{</code> and
        <code class="literal">}</code> characters:
      </p><pre data-lang="json" class="programlisting">{"k1": "value", "k2": 10}</pre><p>
        As the examples illustrate, JSON arrays and objects can contain
        scalar values that are strings or numbers, the JSON null
        literal, or the JSON boolean true or false literals. Keys in
        JSON objects must be strings. Temporal (date, time, or datetime)
        scalar values are also permitted:
      </p><pre data-lang="json" class="programlisting">["12:18:29.000000", "2015-07-29", "2015-07-29 12:18:29.000000"]</pre><p>
        Nesting is permitted within JSON array elements and JSON object
        key values:
      </p><pre data-lang="json" class="programlisting">[99, {"id": "HK500", "cost": 75.99}, ["hot", "cold"]]
{"k1": "value", "k2": [10, 20]}</pre><p>
        You can also obtain JSON values from a number of functions
        supplied by MySQL for this purpose (see
        <a class="xref" href="functions.html#json-creation-functions" title="12.17.2 Functions That Create JSON Values">Section 12.17.2, “Functions That Create JSON Values”</a>) as well as by casting
        values of other types to the <code class="literal">JSON</code> type using
        <a class="link" href="functions.html#function_cast"><code class="literal">CAST(<em class="replaceable"><code>value</code></em> AS
        JSON)</code></a> (see
        <a class="xref" href="data-types.html#json-converting-between-types" title="Converting between JSON and non-JSON values">Converting between JSON and non-JSON values</a>). The next
        several paragraphs describe how MySQL handles JSON values
        provided as input.
      </p><a class="indexterm" name="idm46444335643456"></a><a class="indexterm" name="idm46444335642384"></a><p>
        In MySQL, JSON values are written as strings. MySQL parses any
        string used in a context that requires a JSON value, and
        produces an error if it is not valid as JSON. These contexts
        include inserting a value into a column that has the
        <code class="literal">JSON</code> data type and passing an argument to a
        function that expects a JSON value (usually shown as
        <em class="replaceable"><code>json_doc</code></em> or
        <em class="replaceable"><code>json_val</code></em> in the documentation for
        MySQL JSON functions), as the following examples demonstrate:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Attempting to insert a value into a <code class="literal">JSON</code>
            column succeeds if the value is a valid JSON value, but
            fails if it is not:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t1 (jdoc JSON);</code></strong>
Query OK, 0 rows affected (0.20 sec)

mysql&gt; <strong class="userinput"><code>INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');</code></strong>
Query OK, 1 row affected (0.01 sec)

mysql&gt; <strong class="userinput"><code>INSERT INTO t1 VALUES('[1, 2,');</code></strong>
ERROR 3140 (22032) at line 2: Invalid JSON text:
"Invalid value." at position 6 in value (or column) '[1, 2,'.
</pre><p>
            Positions for <span class="quote">“<span class="quote">at position
            <em class="replaceable"><code>N</code></em></span>”</span> in such error messages
            are 0-based, but should be considered rough indications of
            where the problem in a value actually occurs.
          </p></li><li class="listitem"><p>
            The <a class="link" href="functions.html#function_json-type"><code class="literal">JSON_TYPE()</code></a> function
            expects a JSON argument and attempts to parse it into a JSON
            value. It returns the value's JSON type if it is valid
            and produces an error otherwise:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_TYPE('["a", "b", 1]');</code></strong>
+----------------------------+
| JSON_TYPE('["a", "b", 1]') |
+----------------------------+
| ARRAY                      |
+----------------------------+

mysql&gt; <strong class="userinput"><code>SELECT JSON_TYPE('"hello"');</code></strong>
+----------------------+
| JSON_TYPE('"hello"') |
+----------------------+
| STRING               |
+----------------------+

mysql&gt; <strong class="userinput"><code>SELECT JSON_TYPE('hello');</code></strong>
ERROR 3146 (22032): Invalid data type for JSON data in argument 1
to function json_type; a JSON string or JSON type is required.
</pre></li></ul>
</div>
<p>
        MySQL handles strings used in JSON context using the
        <code class="literal">utf8mb4</code> character set and
        <code class="literal">utf8mb4_bin</code> collation. Strings in other
        character sets are converted to <code class="literal">utf8mb4</code> as
        necessary. (For strings in the <code class="literal">ascii</code> or
        <code class="literal">utf8</code> character sets, no conversion is needed
        because <code class="literal">ascii</code> and <code class="literal">utf8</code> are
        subsets of <code class="literal">utf8mb4</code>.)
      </p><p>
        As an alternative to writing JSON values using literal strings,
        functions exist for composing JSON values from component
        elements. <a class="link" href="functions.html#function_json-array"><code class="literal">JSON_ARRAY()</code></a> takes a
        (possibly empty) list of values and returns a JSON array
        containing those values:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_ARRAY('a', 1, NOW());</code></strong>
+----------------------------------------+
| JSON_ARRAY('a', 1, NOW())              |
+----------------------------------------+
| ["a", 1, "2015-07-27 09:43:47.000000"] |
+----------------------------------------+
</pre><p>
        <a class="link" href="functions.html#function_json-object"><code class="literal">JSON_OBJECT()</code></a> takes a (possibly
        empty) list of key-value pairs and returns a JSON object
        containing those pairs:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_OBJECT('key1', 1, 'key2', 'abc');</code></strong>
+---------------------------------------+
| JSON_OBJECT('key1', 1, 'key2', 'abc') |
+---------------------------------------+
| {"key1": 1, "key2": "abc"}            |
+---------------------------------------+
</pre><p>
        <a class="link" href="functions.html#function_json-merge-preserve"><code class="literal">JSON_MERGE_PRESERVE()</code></a> takes two
        or more JSON documents and returns the combined result:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_MERGE_PRESERVE('["a", 1]', '{"key": "value"}');</code></strong>
+-----------------------------------------------------+
| JSON_MERGE_PRESERVE('["a", 1]', '{"key": "value"}') |
+-----------------------------------------------------+
| ["a", 1, {"key": "value"}]                          |
+-----------------------------------------------------+
1 row in set (0.00 sec)
</pre><p>
        For information about the merging rules, see
        <a class="xref" href="data-types.html#json-normalization" title="Normalization, Merging, and Autowrapping of JSON Values">Normalization, Merging, and Autowrapping of JSON Values</a>.
      </p><p>
        (MySQL 8.0.3 and later also support
        <a class="link" href="functions.html#function_json-merge-patch"><code class="literal">JSON_MERGE_PATCH()</code></a>, which has
        somewhat different behavior. See
        <a class="xref" href="functions.html#json-merge-patch-json-merge-preserve-compared" title="JSON_MERGE_PATCH() compared with JSON_MERGE_PRESERVE()">JSON_MERGE_PATCH() compared with JSON_MERGE_PRESERVE()</a>,
        for information about the differences between these two
        functions.)
      </p><p>
        JSON values can be assigned to user-defined variables:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SET @j = JSON_OBJECT('key', 'value');</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT @j;</code></strong>
+------------------+
| @j               |
+------------------+
| {"key": "value"} |
+------------------+
</pre><p>
        However, user-defined variables cannot be of
        <code class="literal">JSON</code> data type, so although
        <code class="literal">@j</code> in the preceding example looks like a JSON
        value and has the same character set and collation as a JSON
        value, it does <span class="emphasis"><em>not</em></span> have the
        <code class="literal">JSON</code> data type. Instead, the result from
        <a class="link" href="functions.html#function_json-object"><code class="literal">JSON_OBJECT()</code></a> is converted to a
        string when assigned to the variable.
      </p><p>
        Strings produced by converting JSON values have a character set
        of <code class="literal">utf8mb4</code> and a collation of
        <code class="literal">utf8mb4_bin</code>:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT CHARSET(@j), COLLATION(@j);</code></strong>
+-------------+---------------+
| CHARSET(@j) | COLLATION(@j) |
+-------------+---------------+
| utf8mb4     | utf8mb4_bin   |
+-------------+---------------+
</pre><p>
        Because <code class="literal">utf8mb4_bin</code> is a binary collation,
        comparison of JSON values is case-sensitive.
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_ARRAY('x') = JSON_ARRAY('X');</code></strong>
+-----------------------------------+
| JSON_ARRAY('x') = JSON_ARRAY('X') |
+-----------------------------------+
|                                 0 |
+-----------------------------------+
</pre><a class="indexterm" name="idm46444335589632"></a><p>
        Case sensitivity also applies to the JSON
        <code class="literal">null</code>, <code class="literal">true</code>, and
        <code class="literal">false</code> literals, which always must be written
        in lowercase:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_VALID('null'), JSON_VALID('Null'), JSON_VALID('NULL');</code></strong>
+--------------------+--------------------+--------------------+
| JSON_VALID('null') | JSON_VALID('Null') | JSON_VALID('NULL') |
+--------------------+--------------------+--------------------+
|                  1 |                  0 |                  0 |
+--------------------+--------------------+--------------------+

mysql&gt; <strong class="userinput"><code>SELECT CAST('null' AS JSON);</code></strong>
+----------------------+
| CAST('null' AS JSON) |
+----------------------+
| null                 |
+----------------------+
1 row in set (0.00 sec)

mysql&gt; <strong class="userinput"><code>SELECT CAST('NULL' AS JSON);</code></strong>
ERROR 3141 (22032): Invalid JSON text in argument 1 to function cast_as_json:
"Invalid value." at position 0 in 'NULL'.
</pre><p>
        Case sensitivity of the JSON literals differs from that of the
        SQL <code class="literal">NULL</code>, <code class="literal">TRUE</code>, and
        <code class="literal">FALSE</code> literals, which can be written in any
        lettercase:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT ISNULL(null), ISNULL(Null), ISNULL(NULL);</code></strong>
+--------------+--------------+--------------+
| ISNULL(null) | ISNULL(Null) | ISNULL(NULL) |
+--------------+--------------+--------------+
|            1 |            1 |            1 |
+--------------+--------------+--------------+
</pre><a class="indexterm" name="idm46444335576688"></a><p>
        Sometimes it may be necessary or desirable to insert quote
        characters (<code class="literal">"</code> or <code class="literal">'</code>) into a
        JSON document. Assume for this example that you want to insert
        some JSON objects containing strings representing sentences that
        state some facts about MySQL, each paired with an appropriate
        keyword, into a table created using the SQL statement shown
        here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE facts (sentence JSON);</code></strong>
</pre><p>
        Among these keyword-sentence pairs is this one:
      </p><pre data-lang="simple" class="programlisting">mascot: The MySQL mascot is a dolphin named "Sakila".</pre><p>
        One way to insert this as a JSON object into the
        <code class="literal">facts</code> table is to use the MySQL
        <a class="link" href="functions.html#function_json-object"><code class="literal">JSON_OBJECT()</code></a> function. In this
        case, you must escape each quote character using a backslash, as
        shown here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO facts VALUES</code></strong>
     &gt;   <strong class="userinput"><code>(JSON_OBJECT("mascot", "Our mascot is a dolphin named \"Sakila\"."));</code></strong>
</pre><p>
        This does not work in the same way if you insert the value as a
        JSON object literal, in which case, you must use the double
        backslash escape sequence, like this:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO facts VALUES</code></strong>
     &gt;   <strong class="userinput"><code>('{"mascot": "Our mascot is a dolphin named \\"Sakila\\"."}');</code></strong>
</pre><p>
        Using the double backslash keeps MySQL from performing escape
        sequence processing, and instead causes it to pass the string
        literal to the storage engine for processing. After inserting
        the JSON object in either of the ways just shown, you can see
        that the backslashes are present in the JSON column value by
        doing a simple <a class="link" href="sql-statements.html#select" title="13.2.10 SELECT Statement"><code class="literal">SELECT</code></a>, like this:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT sentence FROM facts;</code></strong>
+---------------------------------------------------------+
| sentence                                                |
+---------------------------------------------------------+
| {"mascot": "Our mascot is a dolphin named \"Sakila\"."} |
+---------------------------------------------------------+
</pre><p>
        To look up this particular sentence employing
        <code class="literal">mascot</code> as the key, you can use the
        column-path operator
        <a class="link" href="functions.html#operator_json-column-path"><code class="literal">-&gt;</code></a>,
        as shown here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; SELECT col-&gt;"$.mascot" FROM qtest;
+---------------------------------------------+
| col-&gt;"$.mascot"                             |
+---------------------------------------------+
| "Our mascot is a dolphin named \"Sakila\"." |
+---------------------------------------------+
1 row in set (0.00 sec)</pre><p>
        This leaves the backslashes intact, along with the surrounding
        quote marks. To display the desired value using
        <code class="literal">mascot</code> as the key, but without including the
        surrounding quote marks or any escapes, use the inline path
        operator
        <a class="link" href="functions.html#operator_json-inline-path"><code class="literal">-&gt;&gt;</code></a>,
        like this:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT sentence-&gt;&gt;"$.mascot" FROM facts;</code></strong>
+-----------------------------------------+
| sentence-&gt;&gt;"$.mascot"                   |
+-----------------------------------------+
| Our mascot is a dolphin named "Sakila". |
+-----------------------------------------+
</pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          The previous example does not work as shown if the
          <a class="link" href="server-administration.html#sqlmode_no_backslash_escapes"><code class="literal">NO_BACKSLASH_ESCAPES</code></a> server
          SQL mode is enabled. If this mode is set, a single backslash
          instead of double backslashes can be used to insert the JSON
          object literal, and the backslashes are preserved. If you use
          the <code class="literal">JSON_OBJECT()</code> function when performing
          the insert and this mode is set, you must alternate single and
          double quotes, like this:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>INSERT INTO facts VALUES</code></strong>
     &gt; <strong class="userinput"><code>(JSON_OBJECT('mascot', 'Our mascot is a dolphin named "Sakila".'));</code></strong>
</pre><p>
          See the description of the
          <a class="link" href="functions.html#function_json-unquote"><code class="literal">JSON_UNQUOTE()</code></a> function for
          more information about the effects of this mode on escaped
          characters in JSON values.
</p>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-normalization"></a>Normalization, Merging, and Autowrapping of JSON Values</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335540096"></a><a class="indexterm" name="idm46444335538640"></a><a class="indexterm" name="idm46444335537568"></a><a class="indexterm" name="idm46444335536080"></a><a class="indexterm" name="idm46444335535008"></a><a class="indexterm" name="idm46444335533520"></a><p>
        When a string is parsed and found to be a valid JSON document,
        it is also normalized. This means that members with keys that
        duplicate a key found later in the document, reading from left
        to right, are discarded. The object value produced by the
        following <a class="link" href="functions.html#function_json-object"><code class="literal">JSON_OBJECT()</code></a> call
        includes only the second <code class="literal">key1</code> element because
        that key name occurs earlier in the value, as shown here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def');</code></strong>
+------------------------------------------------------+
| JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def') |
+------------------------------------------------------+
| {"key1": "def", "key2": "abc"}                       |
+------------------------------------------------------+
</pre><p>
        Normalization is also performed when values are inserted into
        JSON columns, as shown here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t1 (c1 JSON);</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO t1 VALUES</code></strong>
     &gt;     <strong class="userinput"><code>('{"x": 17, "x": "red"}'),</code></strong>
     &gt;     <strong class="userinput"><code>('{"x": 17, "x": "red", "x": [3, 5, 7]}');</code></strong>

mysql&gt; <strong class="userinput"><code>SELECT c1 FROM t1;</code></strong>
+------------------+
| c1               |
+------------------+
| {"x": "red"}     |
| {"x": [3, 5, 7]} |
+------------------+
</pre><p>
        This <span class="quote">“<span class="quote">last duplicate key wins</span>”</span> behavior is
        suggested by
        <a class="ulink" href="https://tools.ietf.org/html/rfc7159" target="_top">RFC
        7159</a> and is implemented by most JavaScript parsers. (Bug
        #86866, Bug #26369555)
      </p><p>
        In versions of MySQL prior to 8.0.3, members with keys that
        duplicated a key found earlier in the document were discarded.
        The object value produced by the following
        <a class="link" href="functions.html#function_json-object"><code class="literal">JSON_OBJECT()</code></a> call does not
        include the second <code class="literal">key1</code> element because that
        key name occurs earlier in the value:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def');</code></strong>
+------------------------------------------------------+
| JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def') |
+------------------------------------------------------+
| {"key1": 1, "key2": "abc"}                           |
+------------------------------------------------------+
</pre><p>
        Prior to MySQL 8.0.3, this <span class="quote">“<span class="quote">first duplicate key
        wins</span>”</span> normalization was also performed when inserting
        values into JSON columns.
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t1 (c1 JSON);</code></strong>

mysql&gt; <strong class="userinput"><code>INSERT INTO t1 VALUES</code></strong>
     &gt;     <strong class="userinput"><code>('{"x": 17, "x": "red"}'),</code></strong>
     &gt;     <strong class="userinput"><code>('{"x": 17, "x": "red", "x": [3, 5, 7]}');</code></strong>

mysql&gt; <strong class="userinput"><code>SELECT c1 FROM t1;</code></strong>
+-----------+
| c1        |
+-----------+
| {"x": 17} |
| {"x": 17} |
+-----------+
</pre><p>
        MySQL also discards extra whitespace between keys, values, or
        elements in the original JSON document, and leaves (or inserts,
        when necessary) a single space following each comma
        (<code class="literal">,</code>) or colon (<code class="literal">:</code>) when
        displaying it. This is done to enhance readibility.
      </p><p>
        MySQL functions that produce JSON values (see
        <a class="xref" href="functions.html#json-creation-functions" title="12.17.2 Functions That Create JSON Values">Section 12.17.2, “Functions That Create JSON Values”</a>) always return
        normalized values.
      </p><p>
        To make lookups more efficient, MySQL also sorts the keys of a
        JSON object. <span class="emphasis"><em>You should be aware that the result of
        this ordering is subject to change and not guaranteed to be
        consistent across releases</em></span>.
</p>
<h4><a name="json-merging"></a>Merging JSON Values</h4>
<a class="indexterm" name="idm46444335505104"></a><a class="indexterm" name="idm46444335504032"></a><a class="indexterm" name="idm46444335502960"></a><a class="indexterm" name="idm46444335501888"></a><p>
        Two merging algorithms are supported in MySQL 8.0.3 (and later),
        implemented by the functions
        <a class="link" href="functions.html#function_json-merge-preserve"><code class="literal">JSON_MERGE_PRESERVE()</code></a> and
        <a class="link" href="functions.html#function_json-merge-patch"><code class="literal">JSON_MERGE_PATCH()</code></a>. These differ
        in how they handle duplicate keys:
        <a class="link" href="functions.html#function_json-merge-preserve"><code class="literal">JSON_MERGE_PRESERVE()</code></a> retains
        values for duplicate keys, while
        <a class="link" href="functions.html#function_json-merge-patch"><code class="literal">JSON_MERGE_PATCH()</code></a> discards all
        but the last value. The next few paragraphs explain how each of
        these two functions handles the merging of different
        combinations of JSON documents (that is, of objects and arrays).
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          <a class="link" href="functions.html#function_json-merge-preserve"><code class="literal">JSON_MERGE_PRESERVE()</code></a> is the
          same as the <code class="literal">JSON_MERGE()</code> function found in
          previous versions of MySQL (renamed in MySQL 8.0.3).
          <code class="literal">JSON_MERGE()</code> is still supported as an alias
          for <code class="literal">JSON_MERGE_PRESERVE()</code> in MySQL
          8.0, but is deprecated and subject to removal in
          a future release.
</p>
</div>
<p><b>Merging arrays. </b>
          In contexts that combine multiple arrays, the arrays are
          merged into a single array.
          <code class="literal">JSON_MERGE_PRESERVE()</code> does this by
          concatenating arrays named later to the end of the first
          array. <code class="literal">JSON_MERGE_PATCH()</code> considers each
          argument as an array consisting of a single element (thus
          having 0 as its index) and then applies <span class="quote">“<span class="quote">last duplicate
          key wins</span>”</span> logic to select only the last argument. You
          can compare the results shown by this query:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT</code></strong>
    -&gt;   <strong class="userinput"><code>JSON_MERGE_PRESERVE('[1, 2]', '["a", "b", "c"]', '[true, false]') AS Preserve,</code></strong>
    -&gt;   <strong class="userinput"><code>JSON_MERGE_PATCH('[1, 2]', '["a", "b", "c"]', '[true, false]') AS Patch\G</code></strong>
*************************** 1. row ***************************
Preserve: [1, 2, "a", "b", "c", true, false]
   Patch: [true, false]
</pre><p>
        Multiple objects when merged produce a single object.
        <code class="literal">JSON_MERGE_PRESERVE()</code> handles multiple
        objects having the same key by combining all unique values for
        that key in an array; this array is then used as the value for
        that key in the result. <code class="literal">JSON_MERGE_PATCH()</code>
        discards values for which duplicate keys are found, working from
        left to right, so that the result contains only the last value
        for that key. The following query illustrates the difference in
        the results for the duplicate key <code class="literal">a</code>:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT</code></strong>
    -&gt;   <strong class="userinput"><code>JSON_MERGE_PRESERVE('{"a": 1, "b": 2}', '{"c": 3, "a": 4}', '{"c": 5, "d": 3}') AS Preserve,</code></strong>
    -&gt;   <strong class="userinput"><code>JSON_MERGE_PATCH('{"a": 3, "b": 2}', '{"c": 3, "a": 4}', '{"c": 5, "d": 3}') AS Patch\G</code></strong>
*************************** 1. row ***************************
Preserve: {"a": [1, 4], "b": 2, "c": [3, 5], "d": 3}
   Patch: {"a": 4, "b": 2, "c": 5, "d": 3}
</pre><p>
        Nonarray values used in a context that requires an array value
        are autowrapped: The value is surrounded by <code class="literal">[</code>
        and <code class="literal">]</code> characters to convert it to an array.
        In the following statement, each argument is autowrapped as an
        array (<code class="literal">[1]</code>, <code class="literal">[2]</code>). These
        are then merged to produce a single result array; as in the
        previous two cases, <code class="literal">JSON_MERGE_PRESERVE()</code>
        combines values having the same key while
        <code class="literal">JSON_MERGE_PATCH()</code> discards values for all
        duplicate keys except the last, as shown here:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT</code></strong>
	  -&gt;   <strong class="userinput"><code>JSON_MERGE_PRESERVE('1', '2') AS Preserve,</code></strong>
	  -&gt;   <strong class="userinput"><code>JSON_MERGE_PATCH('1', '2') AS Patch\G</code></strong>
*************************** 1. row ***************************
Preserve: [1, 2]
   Patch: 2
</pre><p>
        Array and object values are merged by autowrapping the object as
        an array and merging the arrays by combining values or by
        <span class="quote">“<span class="quote">last duplicate key wins</span>”</span> according to the choice
        of merging function (<code class="literal">JSON_MERGE_PRESERVE()</code> or
        <code class="literal">JSON_MERGE_PATCH()</code>, respectively), as can be
        seen in this example:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT</code></strong>
	  -&gt;   <strong class="userinput"><code>JSON_MERGE_PRESERVE('[10, 20]', '{"a": "x", "b": "y"}') AS Preserve,</code></strong>
	  -&gt;   <strong class="userinput"><code>JSON_MERGE_PATCH('[10, 20]', '{"a": "x", "b": "y"}') AS Patch\G</code></strong>
*************************** 1. row ***************************
Preserve: [10, 20, {"a": "x", "b": "y"}]
   Patch: {"a": "x", "b": "y"}
</pre>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-paths"></a>Searching and Modifying JSON Values</h3>

</div>

</div>

</div>
<p>
        A JSON path expression selects a value within a JSON document.
      </p><p>
        Path expressions are useful with functions that extract parts of
        or modify a JSON document, to specify where within that document
        to operate. For example, the following query extracts from a
        JSON document the value of the member with the
        <code class="literal">name</code> key:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('{"id": 14, "name": "Aztalan"}', '$.name');</code></strong>
+---------------------------------------------------------+
| JSON_EXTRACT('{"id": 14, "name": "Aztalan"}', '$.name') |
+---------------------------------------------------------+
| "Aztalan"                                               |
+---------------------------------------------------------+
</pre><p>
        Path syntax uses a leading <code class="literal">$</code> character to
        represent the JSON document under consideration, optionally
        followed by selectors that indicate successively more specific
        parts of the document:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            A period followed by a key name names the member in an
            object with the given key. The key name must be specified
            within double quotation marks if the name without quotes is
            not legal within path expressions (for example, if it
            contains a space).
          </p></li><li class="listitem"><p>
            <code class="literal">[<em class="replaceable"><code>N</code></em>]</code> appended
            to a <em class="replaceable"><code>path</code></em> that selects an array
            names the value at position <em class="replaceable"><code>N</code></em>
            within the array. Array positions are integers beginning
            with zero. If <em class="replaceable"><code>path</code></em> does not
            select an array value, <em class="replaceable"><code>path</code></em>[0]
            evaluates to the same value as
            <em class="replaceable"><code>path</code></em>:
          </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_SET('"x"', '$[0]', 'a');</code></strong>
+------------------------------+
| JSON_SET('"x"', '$[0]', 'a') |
+------------------------------+
| "a"                          |
+------------------------------+
1 row in set (0.00 sec)
</pre></li><li class="listitem"><p>
            <code class="literal">[<em class="replaceable"><code>M</code></em> to
            <em class="replaceable"><code>N</code></em>]</code> specifies a subset
            or range of array values starting with the value at position
            <em class="replaceable"><code>M</code></em>, and ending with the value at
            position <em class="replaceable"><code>N</code></em>.
          </p><p>
            <code class="literal">last</code> is supported as a synonym for the
            index of the rightmost array element. Relative addressing of
            array elements is also supported. If
            <em class="replaceable"><code>path</code></em> does not select an array
            value, <em class="replaceable"><code>path</code></em>[last] evaluates to
            the same value as <em class="replaceable"><code>path</code></em>, as shown
            later in this section (see
            <a class="xref" href="data-types.html#json-paths-last" title="Rightmost array element">Rightmost array element</a>).
          </p></li><li class="listitem"><p>
            Paths can contain <code class="literal">*</code> or
            <code class="literal">**</code> wildcards:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                <code class="literal">.[*]</code> evaluates to the values of all
                members in a JSON object.
              </p></li><li class="listitem"><p>
                <code class="literal">[*]</code> evaluates to the values of all
                elements in a JSON array.
              </p></li><li class="listitem"><p>
                <code class="literal"><em class="replaceable"><code>prefix</code></em>**<em class="replaceable"><code>suffix</code></em></code>
                evaluates to all paths that begin with the named prefix
                and end with the named suffix.
</p></li></ul>
</div>
</li><li class="listitem"><p>
            A path that does not exist in the document (evaluates to
            nonexistent data) evaluates to <code class="literal">NULL</code>.
</p></li></ul>
</div>
<p>
        Let <code class="literal">$</code> refer to this JSON array with three
        elements:
      </p><pre data-lang="json" class="programlisting">[3, {"a": [5, 6], "b": 10}, [99, 100]]</pre><p>
        Then:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">$[0]</code> evaluates to <code class="literal">3</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[1]</code> evaluates to <code class="literal">{"a": [5, 6],
            "b": 10}</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[2]</code> evaluates to <code class="literal">[99,
            100]</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[3]</code> evaluates to <code class="literal">NULL</code>
            (it refers to the fourth array element, which does not
            exist).
</p></li></ul>
</div>
<p>
        Because <code class="literal">$[1]</code> and <code class="literal">$[2]</code>
        evaluate to nonscalar values, they can be used as the basis for
        more-specific path expressions that select nested values.
        Examples:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">$[1].a</code> evaluates to <code class="literal">[5,
            6]</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[1].a[1]</code> evaluates to
            <code class="literal">6</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[1].b</code> evaluates to
            <code class="literal">10</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$[2][0]</code> evaluates to
            <code class="literal">99</code>.
</p></li></ul>
</div>
<p>
        As mentioned previously, path components that name keys must be
        quoted if the unquoted key name is not legal in path
        expressions. Let <code class="literal">$</code> refer to this value:
      </p><pre data-lang="json" class="programlisting">{"a fish": "shark", "a bird": "sparrow"}</pre><p>
        The keys both contain a space and must be quoted:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">$."a fish"</code> evaluates to
            <code class="literal">shark</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">$."a bird"</code> evaluates to
            <code class="literal">sparrow</code>.
</p></li></ul>
</div>
<p>
        Paths that use wildcards evaluate to an array that can contain
        multiple values:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('{"a": 1, "b": 2, "c": [3, 4, 5]}', '$.*');</code></strong>
+---------------------------------------------------------+
| JSON_EXTRACT('{"a": 1, "b": 2, "c": [3, 4, 5]}', '$.*') |
+---------------------------------------------------------+
| [1, 2, [3, 4, 5]]                                       |
+---------------------------------------------------------+
mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('{"a": 1, "b": 2, "c": [3, 4, 5]}', '$.c[*]');</code></strong>
+------------------------------------------------------------+
| JSON_EXTRACT('{"a": 1, "b": 2, "c": [3, 4, 5]}', '$.c[*]') |
+------------------------------------------------------------+
| [3, 4, 5]                                                  |
+------------------------------------------------------------+
</pre><p>
        In the following example, the path <code class="literal">$**.b</code>
        evaluates to multiple paths (<code class="literal">$.a.b</code> and
        <code class="literal">$.c.b</code>) and produces an array of the matching
        path values:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('{"a": {"b": 1}, "c": {"b": 2}}', '$**.b');</code></strong>
+---------------------------------------------------------+
| JSON_EXTRACT('{"a": {"b": 1}, "c": {"b": 2}}', '$**.b') |
+---------------------------------------------------------+
| [1, 2]                                                  |
+---------------------------------------------------------+
</pre><p><a name="json-paths-ranges"></a><b>Ranges from JSON arrays. </b>
          You can use ranges with the <code class="literal">to</code> keyword to
          specify subsets of JSON arrays. For example, <code class="literal">$[1 to
          3]</code> includes the second, third, and fourth elements
          of an array, as shown here:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('[1, 2, 3, 4, 5]', '$[1 to 3]');</code></strong>
+----------------------------------------------+
| JSON_EXTRACT('[1, 2, 3, 4, 5]', '$[1 to 3]') |
+----------------------------------------------+
| [2, 3, 4]                                    |
+----------------------------------------------+
1 row in set (0.00 sec)
</pre><p>
        The syntax is <code class="literal"><em class="replaceable"><code>M</code></em> to
        <em class="replaceable"><code>N</code></em></code>, where
        <em class="replaceable"><code>M</code></em> and <em class="replaceable"><code>N</code></em>
        are, respectively, the first and last indexes of a range of
        elements from a JSON array. <em class="replaceable"><code>N</code></em> must be
        greater than <em class="replaceable"><code>M</code></em>;
        <em class="replaceable"><code>M</code></em> must be greater than or equal to 0.
        Array elements are indexed beginning with 0.
      </p><p>
        You can use ranges in contexts where wildcards are supported.
      </p><p><a name="json-paths-last"></a><b>Rightmost array element. </b>
          The <code class="literal">last</code> keyword is supported as a synonym
          for the index of the last element in an array. Expressions of
          the form <code class="literal">last -
          <em class="replaceable"><code>N</code></em></code> can be used for
          relative addressing, and within range definitions, like this:
        </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_EXTRACT('[1, 2, 3, 4, 5]', '$[last-3 to last-1]');</code></strong>
+--------------------------------------------------------+
| JSON_EXTRACT('[1, 2, 3, 4, 5]', '$[last-3 to last-1]') |
+--------------------------------------------------------+
| [2, 3, 4]                                              |
+--------------------------------------------------------+
1 row in set (0.01 sec)
</pre><p>
        If the path is evaluated against a value that is not an array,
        the result of the evaluation is the same as if the value had
        been wrapped in a single-element array:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; SELECT JSON_REPLACE('"Sakila"', '$[last]', 10);
+-----------------------------------------+
| JSON_REPLACE('"Sakila"', '$[last]', 10) |
+-----------------------------------------+
| 10                                      |
+-----------------------------------------+
1 row in set (0.00 sec)</pre><p>
        You can use
        <a class="link" href="functions.html#operator_json-column-path"><code class="literal"><em class="replaceable"><code>column</code></em>-&gt;<em class="replaceable"><code>path</code></em></code></a>
        with a JSON column identifier and JSON path expression as a
        synonym for
        <a class="link" href="functions.html#function_json-extract"><code class="literal">JSON_EXTRACT(<em class="replaceable"><code>column</code></em>,
        <em class="replaceable"><code>path</code></em>)</code></a>. See
        <a class="xref" href="functions.html#json-search-functions" title="12.17.3 Functions That Search JSON Values">Section 12.17.3, “Functions That Search JSON Values”</a>, for more information.
        See also <a class="xref" href="sql-statements.html#json-column-indirect-index" title="Indexing a Generated Column to Provide a JSON Column Index">Indexing a Generated Column to Provide a JSON Column Index</a>.
      </p><p>
        Some functions take an existing JSON document, modify it in some
        way, and return the resulting modified document. Path
        expressions indicate where in the document to make changes. For
        example, the <a class="link" href="functions.html#function_json-set"><code class="literal">JSON_SET()</code></a>,
        <a class="link" href="functions.html#function_json-insert"><code class="literal">JSON_INSERT()</code></a>, and
        <a class="link" href="functions.html#function_json-replace"><code class="literal">JSON_REPLACE()</code></a> functions each
        take a JSON document, plus one or more path-value pairs that
        describe where to modify the document and the values to use. The
        functions differ in how they handle existing and nonexisting
        values within the document.
      </p><p>
        Consider this document:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; SET @j = '["a", {"b": [true, false]}, [10, 20]]';</pre><p>
        <a class="link" href="functions.html#function_json-set"><code class="literal">JSON_SET()</code></a> replaces values for
        paths that exist and adds values for paths that do not exist:.
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_SET(@j, '$[1].b[0]', 1, '$[2][2]', 2);</code></strong>
+--------------------------------------------+
| JSON_SET(@j, '$[1].b[0]', 1, '$[2][2]', 2) |
+--------------------------------------------+
| ["a", {"b": [1, false]}, [10, 20, 2]]      |
+--------------------------------------------+
</pre><p>
        In this case, the path <code class="literal">$[1].b[0]</code> selects an
        existing value (<code class="literal">true</code>), which is replaced with
        the value following the path argument (<code class="literal">1</code>).
        The path <code class="literal">$[2][2]</code> does not exist, so the
        corresponding value (<code class="literal">2</code>) is added to the value
        selected by <code class="literal">$[2]</code>.
      </p><p>
        <a class="link" href="functions.html#function_json-insert"><code class="literal">JSON_INSERT()</code></a> adds new values but
        does not replace existing values:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_INSERT(@j, '$[1].b[0]', 1, '$[2][2]', 2);</code></strong>
+-----------------------------------------------+
| JSON_INSERT(@j, '$[1].b[0]', 1, '$[2][2]', 2) |
+-----------------------------------------------+
| ["a", {"b": [true, false]}, [10, 20, 2]]      |
+-----------------------------------------------+
</pre><p>
        <a class="link" href="functions.html#function_json-replace"><code class="literal">JSON_REPLACE()</code></a> replaces existing
        values and ignores new values:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_REPLACE(@j, '$[1].b[0]', 1, '$[2][2]', 2);</code></strong>
+------------------------------------------------+
| JSON_REPLACE(@j, '$[1].b[0]', 1, '$[2][2]', 2) |
+------------------------------------------------+
| ["a", {"b": [1, false]}, [10, 20]]             |
+------------------------------------------------+
</pre><p>
        The path-value pairs are evaluated left to right. The document
        produced by evaluating one pair becomes the new value against
        which the next pair is evaluated.
      </p><p>
        <code class="literal">JSON_REMOVE()</code> takes a JSON document and one
        or more paths that specify values to be removed from the
        document. The return value is the original document minus the
        values selected by paths that exist within the document:
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>SELECT JSON_REMOVE(@j, '$[2]', '$[1].b[1]', '$[1].b[1]');</code></strong>
+---------------------------------------------------+
| JSON_REMOVE(@j, '$[2]', '$[1].b[1]', '$[1].b[1]') |
+---------------------------------------------------+
| ["a", {"b": [true]}]                              |
+---------------------------------------------------+
</pre><p>
        The paths have these effects:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">$[2]</code> matches <code class="literal">[10, 20]</code>
            and removes it.
          </p></li><li class="listitem"><p>
            The first instance of <code class="literal">$[1].b[1]</code> matches
            <code class="literal">false</code> in the <code class="literal">b</code> element
            and removes it.
          </p></li><li class="listitem"><p>
            The second instance of <code class="literal">$[1].b[1]</code> matches
            nothing: That element has already been removed, the path no
            longer exists, and has no effect.
</p></li></ul>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-path-syntax"></a>JSON Path Syntax</h3>

</div>

</div>

</div>
<p>
        Many of the JSON functions supported by MySQL and described
        elsewhere in this Manual (see <a class="xref" href="functions.html#json-functions" title="12.17 JSON Functions">Section 12.17, “JSON Functions”</a>)
        require a path expression in order to identify a specific
        element in a JSON document. A path consists of the path's
        scope followed by one or more path legs. For paths used in MySQL
        JSON functions, the scope is always the document being searched
        or otherwise operated on, represented by a leading
        <code class="literal">$</code> character. Path legs are separated by
        period characters (<code class="literal">.</code>). Cells in arrays are
        represented by
        <code class="literal">[<em class="replaceable"><code>N</code></em>]</code>, where
        <em class="replaceable"><code>N</code></em> is a non-negative integer. Names of
        keys must be double-quoted strings or valid ECMAScript
        identifiers (see
        <code class="uri">http://www.ecma-international.org/ecma-262/5.1/#sec-7.6</code>).
        Path expressions, like JSON text, should be encoded using the
        <code class="literal">ascii</code>, <code class="literal">utf8</code>, or
        <code class="literal">utf8mb4</code> character set. Other character
        encodings are implicitly coerced to <code class="literal">utf8mb4</code>.
        The complete syntax is shown here:
      </p><pre data-lang="clike" class="programlisting"><em class="replaceable"><code>pathExpression</code></em>:
    <em class="replaceable"><code>scope</code></em>[(<em class="replaceable"><code>pathLeg</code></em>)*]

<em class="replaceable"><code>pathLeg</code></em>:
    <em class="replaceable"><code>member</code></em> | <em class="replaceable"><code>arrayLocation</code></em> | <em class="replaceable"><code>doubleAsterisk</code></em>

<em class="replaceable"><code>member</code></em>:
    <em class="replaceable"><code>period</code></em> ( <em class="replaceable"><code>keyName</code></em> | <em class="replaceable"><code>asterisk</code></em> )

<em class="replaceable"><code>arrayLocation</code></em>:
    <em class="replaceable"><code>leftBracket</code></em> ( <em class="replaceable"><code>nonNegativeInteger</code></em> | <em class="replaceable"><code>asterisk</code></em> ) <em class="replaceable"><code>rightBracket</code></em>

<em class="replaceable"><code>keyName</code></em>:
    <em class="replaceable"><code>ESIdentifier</code></em> | <em class="replaceable"><code>doubleQuotedString</code></em>

<em class="replaceable"><code>doubleAsterisk</code></em>:
    '**'

<em class="replaceable"><code>period</code></em>:
    '.'

<em class="replaceable"><code>asterisk</code></em>:
    '*'

<em class="replaceable"><code>leftBracket</code></em>:
    '['

<em class="replaceable"><code>rightBracket</code></em>:
    ']'
</pre><p>
        As noted previously, in MySQL, the scope of the path is always
        the document being operated on, represented as
        <code class="literal">$</code>. You can use <code class="literal">'$'</code> as a
        synonynm for the document in JSON path expressions.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Note
</div>
<p>
          Some implementations support column references for scopes of
          JSON paths; currently, MySQL does not support these.
</p>
</div>
<p>
        The wildcard <code class="literal">*</code> and <code class="literal">**</code>
        tokens are used as follows:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">.*</code> represents the values of all members
            in the object.
          </p></li><li class="listitem"><p>
            <code class="literal">[*]</code> represents the values of all cells in
            the array.
          </p></li><li class="listitem"><p>
            <code class="literal">[<em class="replaceable"><code>prefix</code></em>]**<em class="replaceable"><code>suffix</code></em></code>
            represents all paths beginning with
            <em class="replaceable"><code>prefix</code></em> and ending with
            <em class="replaceable"><code>suffix</code></em>.
            <em class="replaceable"><code>prefix</code></em> is optional, while
            <em class="replaceable"><code>suffix</code></em> is required; in other
            words, a path may not end in <code class="literal">**</code>.
          </p><p>
            In addition, a path may not contain the sequence
            <code class="literal">***</code>.
</p></li></ul>
</div>
<p>
        For path syntax examples, see the descriptions of the various
        JSON functions that take paths as arguments, such as
        <a class="link" href="functions.html#function_json-contains-path"><code class="literal">JSON_CONTAINS_PATH()</code></a>,
        <a class="link" href="functions.html#function_json-set"><code class="literal">JSON_SET()</code></a>, and
        <a class="link" href="functions.html#function_json-replace"><code class="literal">JSON_REPLACE()</code></a>. For examples
        which include the use of the <code class="literal">*</code> and
        <code class="literal">**</code> wildcards, see the description of the
        <a class="link" href="functions.html#function_json-search"><code class="literal">JSON_SEARCH()</code></a> function.
      </p><p>
        MySQL 8.0.2 and later also supports range notation for subsets
        of JSON arrays using the <code class="literal">to</code> keyword (such as
        <code class="literal">$[2 to 10]</code>), as well as the
        <code class="literal">last</code> keyword as a synonym for the rightmost
        element of an array. See <a class="xref" href="data-types.html#json-paths" title="Searching and Modifying JSON Values">Searching and Modifying JSON Values</a>, for more
        information and examples.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-comparison"></a>Comparison and Ordering of JSON Values</h3>

</div>

</div>

</div>
<p>
        JSON values can be compared using the
        <a class="link" href="functions.html#operator_equal"><code class="literal">=</code></a>,
        <a class="link" href="functions.html#operator_less-than"><code class="literal">&lt;</code></a>,
        <a class="link" href="functions.html#operator_less-than-or-equal"><code class="literal">&lt;=</code></a>,
        <a class="link" href="functions.html#operator_greater-than"><code class="literal">&gt;</code></a>,
        <a class="link" href="functions.html#operator_greater-than-or-equal"><code class="literal">&gt;=</code></a>,
        <a class="link" href="functions.html#operator_not-equal"><code class="literal">&lt;&gt;</code></a>,
        <a class="link" href="functions.html#operator_not-equal"><code class="literal">!=</code></a>, and
        <a class="link" href="functions.html#operator_equal-to"><code class="literal">&lt;=&gt;</code></a>
        operators.
      </p><p>
        The following comparison operators and functions are not yet
        supported with JSON values:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <a class="link" href="functions.html#operator_between"><code class="literal">BETWEEN</code></a>
          </p></li><li class="listitem"><p>
            <a class="link" href="functions.html#operator_in"><code class="literal">IN()</code></a>
          </p></li><li class="listitem"><p>
            <a class="link" href="functions.html#function_greatest"><code class="literal">GREATEST()</code></a>
          </p></li><li class="listitem"><p>
            <a class="link" href="functions.html#function_least"><code class="literal">LEAST()</code></a>
</p></li></ul>
</div>
<p>
        A workaround for the comparison operators and functions just
        listed is to cast JSON values to a native MySQL numeric or
        string data type so they have a consistent non-JSON scalar type.
      </p><p>
        Comparison of JSON values takes place at two levels. The first
        level of comparison is based on the JSON types of the compared
        values. If the types differ, the comparison result is determined
        solely by which type has higher precedence. If the two values
        have the same JSON type, a second level of comparison occurs
        using type-specific rules.
      </p><p>
        The following list shows the precedences of JSON types, from
        highest precedence to the lowest. (The type names are those
        returned by the <a class="link" href="functions.html#function_json-type"><code class="literal">JSON_TYPE()</code></a>
        function.) Types shown together on a line have the same
        precedence. Any value having a JSON type listed earlier in the
        list compares greater than any value having a JSON type listed
        later in the list.
      </p><pre data-lang="simple" class="programlisting">BLOB
BIT
OPAQUE
DATETIME
TIME
DATE
BOOLEAN
ARRAY
OBJECT
STRING
INTEGER, DOUBLE
NULL</pre><p>
        For JSON values of the same precedence, the comparison rules are
        type specific:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            <code class="literal">BLOB</code>
          </p><p>
            The first <em class="replaceable"><code>N</code></em> bytes of the two
            values are compared, where <em class="replaceable"><code>N</code></em> is
            the number of bytes in the shorter value. If the first
            <em class="replaceable"><code>N</code></em> bytes of the two values are
            identical, the shorter value is ordered before the longer
            value.
          </p></li><li class="listitem"><p>
            <code class="literal">BIT</code>
          </p><p>
            Same rules as for <code class="literal">BLOB</code>.
          </p></li><li class="listitem"><p>
            <code class="literal">OPAQUE</code>
          </p><p>
            Same rules as for <code class="literal">BLOB</code>.
            <code class="literal">OPAQUE</code> values are values that are not
            classified as one of the other types.
          </p></li><li class="listitem"><p>
            <code class="literal">DATETIME</code>
          </p><p>
            A value that represents an earlier point in time is ordered
            before a value that represents a later point in time. If two
            values originally come from the MySQL
            <code class="literal">DATETIME</code> and <code class="literal">TIMESTAMP</code>
            types, respectively, they are equal if they represent the
            same point in time.
          </p></li><li class="listitem"><p>
            <code class="literal">TIME</code>
          </p><p>
            The smaller of two time values is ordered before the larger
            one.
          </p></li><li class="listitem"><p>
            <code class="literal">DATE</code>
          </p><p>
            The earlier date is ordered before the more recent date.
          </p></li><li class="listitem"><p>
            <code class="literal">ARRAY</code>
          </p><p>
            Two JSON arrays are equal if they have the same length and
            values in corresponding positions in the arrays are equal.
          </p><p>
            If the arrays are not equal, their order is determined by
            the elements in the first position where there is a
            difference. The array with the smaller value in that
            position is ordered first. If all values of the shorter
            array are equal to the corresponding values in the longer
            array, the shorter array is ordered first.
          </p><p>
            Example:
          </p><pre data-lang="simple" class="programlisting">[] &lt; ["a"] &lt; ["ab"] &lt; ["ab", "cd", "ef"] &lt; ["ab", "ef"]</pre></li><li class="listitem"><p>
            <code class="literal">BOOLEAN</code>
          </p><p>
            The JSON false literal is less than the JSON true literal.
          </p></li><li class="listitem"><p>
            <code class="literal">OBJECT</code>
          </p><p>
            Two JSON objects are equal if they have the same set of
            keys, and each key has the same value in both objects.
          </p><p>
            Example:
          </p><pre data-lang="simple" class="programlisting">{"a": 1, "b": 2} = {"b": 2, "a": 1}</pre><p>
            The order of two objects that are not equal is unspecified
            but deterministic.
          </p></li><li class="listitem"><p>
            <code class="literal">STRING</code>
          </p><p>
            Strings are ordered lexically on the first
            <em class="replaceable"><code>N</code></em> bytes of the
            <code class="literal">utf8mb4</code> representation of the two strings
            being compared, where <em class="replaceable"><code>N</code></em> is the
            length of the shorter string. If the first
            <em class="replaceable"><code>N</code></em> bytes of the two strings are
            identical, the shorter string is considered smaller than the
            longer string.
          </p><p>
            Example:
          </p><pre data-lang="simple" class="programlisting">"a" &lt; "ab" &lt; "b" &lt; "bc"</pre><p>
            This ordering is equivalent to the ordering of SQL strings
            with collation <code class="literal">utf8mb4_bin</code>. Because
            <code class="literal">utf8mb4_bin</code> is a binary collation,
            comparison of JSON values is case-sensitive:
          </p><pre data-lang="simple" class="programlisting">"A" &lt; "a"</pre></li><li class="listitem"><p>
            <code class="literal">INTEGER</code>, <code class="literal">DOUBLE</code>
          </p><p>
            JSON values can contain exact-value numbers and
            approximate-value numbers. For a general discussion of these
            types of numbers, see <a class="xref" href="language-structure.html#number-literals" title="9.1.2 Numeric Literals">Section 9.1.2, “Numeric Literals”</a>.
          </p><p>
            The rules for comparing native MySQL numeric types are
            discussed in <a class="xref" href="functions.html#type-conversion" title="12.2 Type Conversion in Expression Evaluation">Section 12.2, “Type Conversion in Expression Evaluation”</a>, but the
            rules for comparing numbers within JSON values differ
            somewhat:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                In a comparison between two columns that use the native
                MySQL <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a> and
                <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> numeric types,
                respectively, it is known that all comparisons involve
                an integer and a double, so the integer is converted to
                double for all rows. That is, exact-value numbers are
                converted to approximate-value numbers.
              </p></li><li class="listitem"><p>
                On the other hand, if the query compares two JSON
                columns containing numbers, it cannot be known in
                advance whether numbers will be integer or double. To
                provide the most consistent behavior across all rows,
                MySQL converts approximate-value numbers to exact-value
                numbers. The resulting ordering is consistent and does
                not lose precision for the exact-value numbers. For
                example, given the scalars 9223372036854775805,
                9223372036854775806, 9223372036854775807 and
                9.223372036854776e18, the order is such as this:
              </p><pre data-lang="sql" class="programlisting">9223372036854775805 &lt; 9223372036854775806 &lt; 9223372036854775807
&lt; 9.223372036854776e18 = 9223372036854776000 &lt; 9223372036854776001</pre></li></ul>
</div>
<p>
            Were JSON comparisons to use the non-JSON numeric comparison
            rules, inconsistent ordering could occur. The usual MySQL
            comparison rules for numbers yield these orderings:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
                Integer comparison:
              </p><pre data-lang="sql" class="programlisting">9223372036854775805 &lt; 9223372036854775806 &lt; 9223372036854775807</pre><p>
                (not defined for 9.223372036854776e18)
              </p></li><li class="listitem"><p>
                Double comparison:
</p><pre data-lang="simple" class="programlisting">9223372036854775805 = 9223372036854775806 = 9223372036854775807 = 9.223372036854776e18</pre></li></ul>
</div>
</li></ul>
</div>
<p>
        For comparison of any JSON value to SQL <code class="literal">NULL</code>,
        the result is <code class="literal">UNKNOWN</code>.
      </p><p>
        For comparison of JSON and non-JSON values, the non-JSON value
        is converted to JSON according to the rules in the following
        table, then the values compared as described previously.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-converting-between-types"></a>Converting between JSON and non-JSON values</h3>

</div>

</div>

</div>
<p>
        The following table provides a summary of the rules that MySQL
        follows when casting between JSON values and values of other
        types:
</p>
<div class="oracle-all">
<a name="json-conversion-rules"></a><p class="title"><b>Table 11.3 JSON Conversion Rules</b></p>
<div class="oracle-all-contents">
<table summary="Conversion rules for the JSON data type"><col width="20%"><col width="40%"><col width="40%"><thead><tr>
            <th scope="col">other type</th>
            <th scope="col">CAST(other type AS JSON)</th>
            <th scope="col">CAST(JSON AS other type)</th>
          </tr></thead><tbody><tr>
            <td scope="row">JSON</td>
            <td>No change</td>
            <td>No change</td>
          </tr><tr>
            <td scope="row">utf8 character type (<code class="literal">utf8mb4</code>,
              <code class="literal">utf8</code>, <code class="literal">ascii</code>)</td>
            <td>The string is parsed into a JSON value.</td>
            <td>The JSON value is serialized into a <code class="literal">utf8mb4</code> string.</td>
          </tr><tr>
            <td scope="row">Other character types</td>
            <td>Other character encodings are implicitly converted to
              <code class="literal">utf8mb4</code> and treated as described for
              utf8 character type.</td>
            <td>The JSON value is serialized into a <code class="literal">utf8mb4</code> string,
              then cast to the other character encoding. The result may
              not be meaningful.</td>
          </tr><tr>
            <td scope="row"><code class="literal">NULL</code></td>
            <td>Results in a <code class="literal">NULL</code> value of type JSON.</td>
            <td>Not applicable.</td>
          </tr><tr>
            <td scope="row">Geometry types</td>
            <td>The geometry value is converted into a JSON document by calling
              <a class="link" href="functions.html#function_st-asgeojson"><code class="literal">ST_AsGeoJSON()</code></a>.</td>
            <td>Illegal operation. Workaround: Pass the result of
              <a class="link" href="functions.html#function_cast"><code class="literal">CAST(<em class="replaceable"><code>json_val</code></em>
              AS CHAR)</code></a> to
              <a class="link" href="functions.html#function_st-geomfromgeojson"><code class="literal">ST_GeomFromGeoJSON()</code></a>.</td>
          </tr><tr>
            <td scope="row">All other types</td>
            <td>Results in a JSON document consisting of a single scalar value.</td>
            <td>Succeeds if the JSON document consists of a single scalar value of the
              target type and that scalar value can be cast to the
              target type. Otherwise, returns <code class="literal">NULL</code>
              and produces a warning.</td>
</tr></tbody></table>
</div>

</div>
<br class="oracle-all-break"><p>
        <code class="literal">ORDER BY</code> and <code class="literal">GROUP BY</code> for
        JSON values works according to these principles:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Ordering of scalar JSON values uses the same rules as in the
            preceding discussion.
          </p></li><li class="listitem"><p>
            For ascending sorts, SQL <code class="literal">NULL</code> orders
            before all JSON values, including the JSON null literal; for
            descending sorts, SQL <code class="literal">NULL</code> orders after
            all JSON values, including the JSON null literal.
          </p></li><li class="listitem"><p>
            Sort keys for JSON values are bound by the value of the
            <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a> system
            variable, so keys that differ only after the first
            <a class="link" href="server-administration.html#sysvar_max_sort_length"><code class="literal">max_sort_length</code></a> bytes
            compare as equal.
          </p></li><li class="listitem"><p>
            Sorting of nonscalar values is not currently supported and a
            warning occurs.
</p></li></ul>
</div>
<p>
        For sorting, it can be beneficial to cast a JSON scalar to some
        other native MySQL type. For example, if a column named
        <code class="literal">jdoc</code> contains JSON objects having a member
        consisting of an <code class="literal">id</code> key and a nonnegative
        value, use this expression to sort by <code class="literal">id</code>
        values:
      </p><pre data-lang="sql" class="programlisting">ORDER BY CAST(JSON_EXTRACT(jdoc, '$.id') AS UNSIGNED)</pre><p>
        If there happens to be a generated column defined to use the
        same expression as in the <code class="literal">ORDER BY</code>, the MySQL
        optimizer recognizes that and considers using the index for the
        query execution plan. See
        <a class="xref" href="optimization.html#generated-column-index-optimizations" title="8.3.11 Optimizer Use of Generated Column Indexes">Section 8.3.11, “Optimizer Use of Generated Column Indexes”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="json-aggregation"></a>Aggregation of JSON Values</h3>

</div>

</div>

</div>
<p>
        For aggregation of JSON values, SQL <code class="literal">NULL</code>
        values are ignored as for other data types.
        Non-<code class="literal">NULL</code> values are converted to a numeric
        type and aggregated, except for
        <a class="link" href="functions.html#function_min"><code class="literal">MIN()</code></a>,
        <a class="link" href="functions.html#function_max"><code class="literal">MAX()</code></a>, and
        <a class="link" href="functions.html#function_group-concat"><code class="literal">GROUP_CONCAT()</code></a>. The conversion to
        number should produce a meaningful result for JSON values that
        are numeric scalars, although (depending on the values)
        truncation and loss of precision may occur. Conversion to number
        of other JSON values may not produce a meaningful result.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="data-type-defaults"></a>11.6 Data Type Default Values</h2>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335144928"></a><a class="indexterm" name="idm46444335143888"></a><a class="indexterm" name="idm46444335142400"></a><a class="indexterm" name="idm46444335141328"></a><a class="indexterm" name="idm46444335139840"></a><a class="indexterm" name="idm46444335138768"></a><p>
      Data type specifications can have explicit or implicit default
      values.
    </p><p>
      A <code class="literal">DEFAULT <em class="replaceable"><code>value</code></em></code>
      clause in a data type specification explicitly indicates a default
      value for a column. Examples:
    </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  i     INT DEFAULT -1,
  c     VARCHAR(10) DEFAULT '',
  price DOUBLE(16,2) DEFAULT 0.00
);</pre><a class="indexterm" name="idm46444335134656"></a><p>
      <code class="literal">SERIAL DEFAULT VALUE</code> is a special case. In the
      definition of an integer column, it is an alias for <code class="literal">NOT
      NULL AUTO_INCREMENT UNIQUE</code>.
    </p><p>
      Some aspects of explicit <code class="literal">DEFAULT</code> clause
      handling are version dependent, as described following.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><a class="xref" href="data-types.html#data-types-defaults-explicit" title="Handling of Explicit Defaults as of MySQL 8.0.13">Handling of Explicit Defaults as of MySQL 8.0.13</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-defaults-explicit-old" title="Handling of Explicit Defaults Prior to MySQL 8.0.13">Handling of Explicit Defaults Prior to MySQL 8.0.13</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-defaults-implicit" title="Handling of Implicit Defaults">Handling of Implicit Defaults</a></p></li></ul>
</div>

<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h3 class="title"><a name="data-types-defaults-explicit"></a>Handling of Explicit Defaults as of MySQL 8.0.13</h3>

</div>

</div>

</div>
<p>
        The default value specified in a <code class="literal">DEFAULT</code>
        clause can be a literal constant or an expression. With one
        exception, enclose expression default values within parentheses
        to distinguish them from literal constant default values.
        Examples:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t1 (
  -- literal defaults
  i INT         DEFAULT 0,
  c VARCHAR(10) DEFAULT '',
  -- expression defaults
  f FLOAT       DEFAULT (RAND() * RAND()),
  b BINARY(16)  DEFAULT (UUID_TO_BIN(UUID())),
  d DATE        DEFAULT (CURRENT_DATE + INTERVAL 1 YEAR),
  p POINT       DEFAULT (Point(0,0)),
  j JSON        DEFAULT (JSON_ARRAY())
);</pre><p>
        The exception is that, for
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns, you can specify
        the <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> function as
        the default, without enclosing parentheses. See
        <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
      </p><p>
        The <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>,
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a>,
        <code class="literal">GEOMETRY</code>, and
        <a class="link" href="data-types.html#json" title="11.5 The JSON Data Type"><code class="literal">JSON</code></a> data types can be assigned a
        default value only if the value is written as an expression,
        even if the expression value is a literal:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            This is permitted (literal default specified as expression):
          </p><pre data-lang="sql" class="programlisting">CREATE TABLE t2 (b BLOB DEFAULT ('abc'));</pre></li><li class="listitem"><p>
            This produces an error (literal default not specified as
            expression):
</p><pre data-lang="sql" class="programlisting">CREATE TABLE t2 (b BLOB DEFAULT 'abc');</pre></li></ul>
</div>
<p>
        Expression default values must adhere to the following rules. An
        error occurs if an expression contains disallowed constructs.
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            Literals, built-in functions (both deterministic and
            nondeterministic), and operators are permitted.
          </p></li><li class="listitem"><p>
            Subqueries, parameters, variables, stored functions, and
            user-defined functions are not permitted.
          </p></li><li class="listitem"><p>
            An expression default value cannot depend on a column that
            has the <code class="literal">AUTO_INCREMENT</code> attribute.
          </p></li><li class="listitem"><p>
            An expression default value for one column can refer to
            other table columns, with the exception that references to
            generated columns or columns with expression default values
            must be to columns that occur earlier in the table
            definition. That is, expression default values cannot
            contain forward references to generated columns or columns
            with expression default values.
          </p><p>
            The ordering constraint also applies to the use of
            <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a> to reorder table
            columns. If the resulting table would have an expression
            default value that contains a forward reference to a
            generated column or column with an expression default value,
            the statement fails.
</p></li></ul>
</div>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<div class="admon-title">
Note
</div>
<p>
          If any component of an expression default value depends on the
          SQL mode, different results may occur for different uses of
          the table unless the SQL mode is the same during all uses.
</p>
</div>
<p>
        For <a class="link" href="sql-statements.html#create-table-like" title="13.1.20.3 CREATE TABLE ... LIKE Statement"><code class="literal">CREATE
        TABLE ... LIKE</code></a> and
        <a class="link" href="sql-statements.html#create-table-select" title="13.1.20.4 CREATE TABLE ... SELECT Statement"><code class="literal">CREATE
        TABLE ... SELECT</code></a>, the destination table preserves
        expression default values from the original table.
      </p><p>
        If an expression default value refers to a nondeterministic
        function, any statement that causes the expression to be
        evaluated is unsafe for statement-based replication. This
        includes statements such as
        <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a>,
        <a class="link" href="sql-statements.html#update" title="13.2.13 UPDATE Statement"><code class="literal">UPDATE</code></a>, and
        <a class="link" href="sql-statements.html#alter-table" title="13.1.9 ALTER TABLE Statement"><code class="literal">ALTER TABLE</code></a>. In this situation,
        if binary logging is disabled, the statement is executed as
        normal. If binary logging is enabled and
        <a class="link" href="replication.html#sysvar_binlog_format"><code class="literal">binlog_format</code></a> is set to
        <code class="literal">STATEMENT</code>, the statement is logged and
        executed but a warning message is written to the error log,
        because replication slaves might diverge. When
        <a class="link" href="replication.html#sysvar_binlog_format"><code class="literal">binlog_format</code></a> is set to
        <code class="literal">MIXED</code> or <code class="literal">ROW</code>, the
        statement is not executed and an error message is written to the
        error log.
      </p><p>
        When inserting a new row, the default value for a column with an
        expression default can be inserted either by omitting the column
        name or by specifying the column as <code class="literal">DEFAULT</code>
        (just as for columns with literal defaults):
      </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t4 (uid BINARY(16) DEFAULT (UUID_TO_BIN(UUID())));</code></strong>
mysql&gt; <strong class="userinput"><code>INSERT INTO t4 () VALUES();</code></strong>
mysql&gt; <strong class="userinput"><code>INSERT INTO t4 () VALUES(DEFAULT);</code></strong>
mysql&gt; <strong class="userinput"><code>SELECT BIN_TO_UUID(uid) AS uid FROM t4;</code></strong>
+--------------------------------------+
| uid                                  |
+--------------------------------------+
| f1109174-94c9-11e8-971d-3bf1095aa633 |
| f110cf9a-94c9-11e8-971d-3bf1095aa633 |
+--------------------------------------+
</pre><p>
        However, the use of
        <a class="link" href="functions.html#function_default"><code class="literal">DEFAULT(<em class="replaceable"><code>col_name</code></em>)</code></a>
        to specify the default value for a named column is permitted
        only for columns that have a literal default value, not for
        columns that have an expression default value.
      </p><p>
        Not all storage engines permit expression default values. For
        those that do not, an
        <a class="link" href="error-handling.html#error_er_unsupported_action_on_default_val_generated"><code class="literal">ER_UNSUPPORTED_ACTION_ON_DEFAULT_VAL_GENERATED</code></a>
        error occurs.
      </p><p>
        If a default value evaluates to a data type that differs from
        the declared column type, implicit coercion to the declared type
        occurs according to the usual MySQL type-conversion rules. See
        <a class="xref" href="functions.html#type-conversion" title="12.2 Type Conversion in Expression Evaluation">Section 12.2, “Type Conversion in Expression Evaluation”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-defaults-explicit-old"></a>Handling of Explicit Defaults Prior to MySQL 8.0.13</h3>

</div>

</div>

</div>
<p>
        With one exception, the default value specified in a
        <code class="literal">DEFAULT</code> clause must be a literal constant; it
        cannot be a function or an expression. This means, for example,
        that you cannot set the default for a date column to be the
        value of a function such as <a class="link" href="functions.html#function_now"><code class="literal">NOW()</code></a>
        or <a class="link" href="functions.html#function_current-date"><code class="literal">CURRENT_DATE</code></a>. The exception is
        that, for <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> columns, you can specify
        <a class="link" href="functions.html#function_current-timestamp"><code class="literal">CURRENT_TIMESTAMP</code></a> as the default.
        See <a class="xref" href="data-types.html#timestamp-initialization" title="11.2.5 Automatic Initialization and Updating for TIMESTAMP and DATETIME">Section 11.2.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”</a>.
      </p><p>
        The <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>,
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a>,
        <code class="literal">GEOMETRY</code>, and
        <a class="link" href="data-types.html#json" title="11.5 The JSON Data Type"><code class="literal">JSON</code></a> data types cannot be
        assigned a default value.
      </p><p>
        If a default value evaluates to a data type that differs from
        the declared column type, implicit coercion to the declared type
        occurs according to the usual MySQL type-conversion rules. See
        <a class="xref" href="functions.html#type-conversion" title="12.2 Type Conversion in Expression Evaluation">Section 12.2, “Type Conversion in Expression Evaluation”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-defaults-implicit"></a>Handling of Implicit Defaults</h3>

</div>

</div>

</div>
<p>
        If a data type specification includes no explicit
        <code class="literal">DEFAULT</code> value, MySQL determines the default
        value as follows:
      </p><p>
        If the column can take <code class="literal">NULL</code> as a value, the
        column is defined with an explicit <code class="literal">DEFAULT
        NULL</code> clause.
      </p><p>
        If the column cannot take <code class="literal">NULL</code> as a value,
        MySQL defines the column with no explicit
        <code class="literal">DEFAULT</code> clause. Exception: If the column is
        defined as part of a <code class="literal">PRIMARY KEY</code> but not
        explicitly as <code class="literal">NOT NULL</code>, MySQL creates it as a
        <code class="literal">NOT NULL</code> column (because <code class="literal">PRIMARY
        KEY</code> columns must be <code class="literal">NOT NULL</code>).
      </p><p>
        For data entry into a <code class="literal">NOT NULL</code> column that
        has no explicit <code class="literal">DEFAULT</code> clause, if an
        <a class="link" href="sql-statements.html#insert" title="13.2.6 INSERT Statement"><code class="literal">INSERT</code></a> or
        <a class="link" href="sql-statements.html#replace" title="13.2.9 REPLACE Statement"><code class="literal">REPLACE</code></a> statement includes no
        value for the column, or an
        <a class="link" href="sql-statements.html#update" title="13.2.13 UPDATE Statement"><code class="literal">UPDATE</code></a> statement sets the column
        to <code class="literal">NULL</code>, MySQL handles the column according
        to the SQL mode in effect at the time:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            If strict SQL mode is enabled, an error occurs for
            transactional tables and the statement is rolled back. For
            nontransactional tables, an error occurs, but if this
            happens for the second or subsequent row of a multiple-row
            statement, the preceding rows will have been inserted.
          </p></li><li class="listitem"><p>
            If strict mode is not enabled, MySQL sets the column to the
            implicit default value for the column data type.
</p></li></ul>
</div>
<p>
        Suppose that a table <code class="literal">t</code> is defined as follows:
      </p><pre data-lang="sql" class="programlisting">CREATE TABLE t (i INT NOT NULL);</pre><p>
        In this case, <code class="literal">i</code> has no explicit default, so
        in strict mode each of the following statements produce an error
        and no row is inserted. When not using strict mode, only the
        third statement produces an error; the implicit default is
        inserted for the first two statements, but the third fails
        because <a class="link" href="functions.html#function_default"><code class="literal">DEFAULT(i)</code></a> cannot produce
        a value:
      </p><pre data-lang="sql" class="programlisting">INSERT INTO t VALUES();
INSERT INTO t VALUES(DEFAULT);
INSERT INTO t VALUES(DEFAULT(i));</pre><p>
        See <a class="xref" href="server-administration.html#sql-mode" title="5.1.11 Server SQL Modes">Section 5.1.11, “Server SQL Modes”</a>.
      </p><p>
        For a given table, the <a class="link" href="sql-statements.html#show-create-table" title="13.7.7.10 SHOW CREATE TABLE Statement"><code class="literal">SHOW CREATE
        TABLE</code></a> statement displays which columns have an
        explicit <code class="literal">DEFAULT</code> clause.
      </p><p>
        Implicit defaults are defined as follows:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            For numeric types, the default is <code class="literal">0</code>, with
            the exception that for integer or floating-point types
            declared with the <code class="literal">AUTO_INCREMENT</code>
            attribute, the default is the next value in the sequence.
          </p></li><li class="listitem"><p>
            For date and time types other than
            <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a>, the default is the
            appropriate <span class="quote">“<span class="quote">zero</span>”</span> value for the type. This is
            also true for <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> if
            the
            <a class="link" href="server-administration.html#sysvar_explicit_defaults_for_timestamp"><code class="literal">explicit_defaults_for_timestamp</code></a>
            system variable is enabled (see
            <a class="xref" href="server-administration.html#server-system-variables" title="5.1.8 Server System Variables">Section 5.1.8, “Server System Variables”</a>). Otherwise, for
            the first <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> column in
            a table, the default value is the current date and time. See
            <a class="xref" href="data-types.html#date-and-time-types" title="11.2 Date and Time Data Types">Section 11.2, “Date and Time Data Types”</a>.
          </p></li><li class="listitem"><p>
            For string types other than
            <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>, the default value is
            the empty string. For <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a>,
            the default is the first enumeration value.
</p></li></ul>
</div>

</div>

</div>

<div class="section">

<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="storage-requirements"></a>11.7 Data Type Storage Requirements</h2>

</div>

</div>

</div>
<a class="indexterm" name="idm46444335017088"></a><a class="indexterm" name="idm46444335015632"></a>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-innodb" title="InnoDB Table Storage Requirements">InnoDB Table Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-ndb" title="NDB Table Storage Requirements">NDB Table Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-numeric" title="Numeric Type Storage Requirements">Numeric Type Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-date-time" title="Date and Time Type Storage Requirements">Date and Time Type Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-strings" title="String Type Storage Requirements">String Type Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-gis" title="Spatial Type Storage Requirements">Spatial Type Storage Requirements</a></p></li><li class="listitem"><p><a class="xref" href="data-types.html#data-types-storage-reqs-json" title="JSON Storage Requirements">JSON Storage Requirements</a></p></li></ul>
</div>
<p>
      The storage requirements for table data on disk depend on several
      factors. Different storage engines represent data types and store
      raw data differently. Table data might be compressed, either for a
      column or an entire row, complicating the calculation of storage
      requirements for a table or column.
    </p><p>
      Despite differences in storage layout on disk, the internal MySQL
      APIs that communicate and exchange information about table rows
      use a consistent data structure that applies across all storage
      engines.
    </p><p>
      This section includes guidelines and information for the storage
      requirements for each data type supported by MySQL, including the
      internal format and size for storage engines that use a fixed-size
      representation for data types. Information is listed by category
      or storage engine.
    </p><a class="indexterm" name="idm46444335004304"></a><p>
      The internal representation of a table has a maximum row size of
      65,535 bytes, even if the storage engine is capable of supporting
      larger rows. This figure excludes
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> or
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> columns, which contribute only
      9 to 12 bytes toward this size. For
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> and
      <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> data, the information is
      stored internally in a different area of memory than the row
      buffer. Different storage engines handle the allocation and
      storage of this data in different ways, according to the method
      they use for handling the corresponding types. For more
      information, see <a class="xref" href="storage-engines.html" title="Chapter 16 Alternative Storage Engines">Chapter 16, <i>Alternative Storage Engines</i></a>, and
      <a class="xref" href="optimization.html#column-count-limit" title="8.4.7 Limits on Table Column Count and Row Size">Section 8.4.7, “Limits on Table Column Count and Row Size”</a>.
</p>
<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-innodb"></a>InnoDB Table Storage Requirements</h3>
</div>
</div>
</div>
<a class="indexterm" name="idm46444334994480"></a><a class="indexterm" name="idm46444334992992"></a><p>
        See <a class="xref" href="innodb-storage-engine.html#innodb-row-format" title="15.10 InnoDB Row Formats">Section 15.10, “InnoDB Row Formats”</a> for information about
        storage requirements for <code class="literal">InnoDB</code> tables.
</p>
</div>

<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-ndb"></a>NDB Table Storage Requirements</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334988368"></a><a class="indexterm" name="idm46444334986880"></a>
<div class="important" style="margin-left: 0.5in; margin-right: 0.5in;">

<div class="admon-title">
Important
</div>
<p>
          <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> tables use
          <span class="firstterm">4-byte alignment</span>; all
          <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> data storage is done in
          multiples of 4 bytes. Thus, a column value that would
          typically take 15 bytes requires 16 bytes in an
          <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> table. For example, in
          <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> tables, the
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a>,
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a>,
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MEDIUMINT</code></a>, and
          <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INTEGER</code></a>
          (<a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a>) column types each require
          4 bytes storage per record due to the alignment factor.
        </p><p>
          Each <code class="literal">BIT(<em class="replaceable"><code>M</code></em>)</code>
          column takes <em class="replaceable"><code>M</code></em> bits of storage
          space. Although an individual
          <a class="link" href="data-types.html#bit-type" title="11.1.5 Bit-Value Type - BIT"><code class="literal">BIT</code></a> column is
          <span class="emphasis"><em>not</em></span> 4-byte aligned,
          <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> reserves 4 bytes (32 bits)
          per row for the first 1-32 bits needed for
          <code class="literal">BIT</code> columns, then another 4 bytes for bits
          33-64, and so on.
        </p><p>
          While a <code class="literal">NULL</code> itself does not require any
          storage space, <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> reserves 4
          bytes per row if the table definition contains any columns
          allowing <code class="literal">NULL</code>, up to 32
          <code class="literal">NULL</code> columns. (If an NDB Cluster table is
          defined with more than 32 <code class="literal">NULL</code> columns up
          to 64 <code class="literal">NULL</code> columns, then 8 bytes per row
          are reserved.)
</p>
</div>
<p>
        Every table using the <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> storage
        engine requires a primary key; if you do not define a primary
        key, a <span class="quote">“<span class="quote">hidden</span>”</span> primary key is created by
        <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a>. This hidden primary key
        consumes 31-35 bytes per table record.
      </p><a class="indexterm" name="idm46444334958176"></a><p>
        You can use the <a class="link" href="mysql-cluster.html#mysql-cluster-programs-ndb-size-pl" title="22.4.28 ndb_size.pl — NDBCLUSTER Size Requirement Estimator"><span class="command"><strong>ndb_size.pl</strong></span></a> Perl script to
        estimate <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> storage requirements.
        It connects to a current MySQL (not NDB Cluster) database and
        creates a report on how much space that database would require
        if it used the <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> storage engine.
        See <a class="xref" href="mysql-cluster.html#mysql-cluster-programs-ndb-size-pl" title="22.4.28 ndb_size.pl — NDBCLUSTER Size Requirement Estimator">Section 22.4.28, “<span class="command"><strong>ndb_size.pl</strong></span> — NDBCLUSTER Size Requirement Estimator”</a> for
        more information.
</p>
</div>

<div class="simplesect">

<div class="titlepage">
<div>

<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-numeric"></a>Numeric Type Storage Requirements</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334950624"></a><a class="indexterm" name="idm46444334949136"></a>
<div class="informaltable">
<table summary="Storage required for numeric data types."><col width="40%"><col width="60%"><thead><tr>
            <th scope="col">Data Type</th>
            <th scope="col">Storage Required</th>
          </tr></thead><tbody><tr>
            <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a></td>
            <td>1 byte</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a></td>
            <td>2 bytes</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MEDIUMINT</code></a></td>
            <td>3 bytes</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a>,
              <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INTEGER</code></a></td>
            <td>4 bytes</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a></td>
            <td>8 bytes</td>
          </tr><tr>
            <td scope="row"><code class="literal">FLOAT(<em class="replaceable"><code>p</code></em>)</code></td>
            <td>4 bytes if 0 &lt;= <em class="replaceable"><code>p</code></em> &lt;= 24, 8 bytes if 25
              &lt;= <em class="replaceable"><code>p</code></em> &lt;= 53</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a></td>
            <td>4 bytes</td>
          </tr><tr>
            <td scope="row"><code class="literal">DOUBLE [PRECISION]</code>,
              <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">REAL</code></a></td>
            <td>8 bytes</td>
          </tr><tr>
            <td scope="row"><code class="literal">DECIMAL(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code>,
              <code class="literal">NUMERIC(<em class="replaceable"><code>M</code></em>,<em class="replaceable"><code>D</code></em>)</code></td>
            <td>Varies; see following discussion</td>
          </tr><tr>
            <td scope="row"><code class="literal">BIT(<em class="replaceable"><code>M</code></em>)</code></td>
            <td>approximately (<em class="replaceable"><code>M</code></em>+7)/8 bytes</td>
</tr></tbody></table>
</div>
<p>
        Values for <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a> (and
        <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">NUMERIC</code></a>) columns are represented
        using a binary format that packs nine decimal (base 10) digits
        into four bytes. Storage for the integer and fractional parts of
        each value are determined separately. Each multiple of nine
        digits requires four bytes, and the <span class="quote">“<span class="quote">leftover</span>”</span>
        digits require some fraction of four bytes. The storage required
        for excess digits is given by the following table.
</p>
<div class="informaltable">
<table summary="Storage required by excess/leftover digits in DECIMAL values."><col width="25%"><col width="25%"><thead><tr>
            <th scope="col">Leftover Digits</th>
            <th scope="col">Number of Bytes</th>
          </tr></thead><tbody><tr>
            <td scope="row">0</td>
            <td>0</td>
          </tr><tr>
            <td scope="row">1</td>
            <td>1</td>
          </tr><tr>
            <td scope="row">2</td>
            <td>1</td>
          </tr><tr>
            <td scope="row">3</td>
            <td>2</td>
          </tr><tr>
            <td scope="row">4</td>
            <td>2</td>
          </tr><tr>
            <td scope="row">5</td>
            <td>3</td>
          </tr><tr>
            <td scope="row">6</td>
            <td>3</td>
          </tr><tr>
            <td scope="row">7</td>
            <td>4</td>
          </tr><tr>
            <td scope="row">8</td>
            <td>4</td>
</tr></tbody></table>
</div>

</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-date-time"></a>Date and Time Type Storage Requirements</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334872256"></a><a class="indexterm" name="idm46444334870768"></a><a class="indexterm" name="idm46444334869280"></a><a class="indexterm" name="idm46444334867792"></a><p>
        For <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> columns, the storage
        required for tables created before MySQL 5.6.4 differs from
        tables created from 5.6.4 on. This is due to a change in 5.6.4
        that permits these types to have a fractional part, which
        requires from 0 to 3 bytes.
</p>
<div class="informaltable">
<table summary="Storage required for date and time data types before MySQL 5.6.4 and as of MySQL 5.6.4."><col width="20%"><col width="40%"><col width="40%"><thead><tr>
            <th scope="col">Data Type</th>
            <th scope="col">Storage Required Before MySQL 5.6.4</th>
            <th scope="col">Storage Required as of MySQL 5.6.4</th>
          </tr></thead><tbody><tr>
            <td scope="row"><a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a></td>
            <td>1 byte</td>
            <td>1 byte</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a></td>
            <td>3 bytes</td>
            <td>3 bytes</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a></td>
            <td>3 bytes</td>
            <td>3 bytes + fractional seconds storage</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a></td>
            <td>8 bytes</td>
            <td>5 bytes + fractional seconds storage</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a></td>
            <td>4 bytes</td>
            <td>4 bytes + fractional seconds storage</td>
</tr></tbody></table>
</div>
<p>
        As of MySQL 5.6.4, storage for
        <a class="link" href="data-types.html#year" title="11.2.4 The YEAR Type"><code class="literal">YEAR</code></a> and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATE</code></a> remains unchanged. However,
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a>,
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a>, and
        <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">TIMESTAMP</code></a> are represented
        differently. <a class="link" href="data-types.html#datetime" title="11.2.2 The DATE, DATETIME, and TIMESTAMP Types"><code class="literal">DATETIME</code></a> is packed
        more efficiently, requiring 5 rather than 8 bytes for the
        nonfractional part, and all three parts have a fractional part
        that requires from 0 to 3 bytes, depending on the fractional
        seconds precision of stored values.
</p>
<div class="informaltable">
<table summary="Required storage for fractional seconds precision."><col width="50%"><col width="50%"><thead><tr>
            <th scope="col">Fractional Seconds Precision</th>
            <th scope="col">Storage Required</th>
          </tr></thead><tbody><tr>
            <td scope="row">0</td>
            <td>0 bytes</td>
          </tr><tr>
            <td scope="row">1, 2</td>
            <td>1 byte</td>
          </tr><tr>
            <td scope="row">3, 4</td>
            <td>2 bytes</td>
          </tr><tr>
            <td scope="row">5, 6</td>
            <td>3 bytes</td>
</tr></tbody></table>
</div>
<p>
        For example, <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(0)</code></a>,
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(2)</code></a>,
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(4)</code></a>, and
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(6)</code></a> use 3, 4, 5, and 6 bytes,
        respectively. <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME</code></a> and
        <a class="link" href="data-types.html#time" title="11.2.3 The TIME Type"><code class="literal">TIME(0)</code></a> are equivalent and
        require the same storage.
      </p><p>
        For details about internal representation of temporal values,
        see <a class="ulink" href="https://dev.mysql.com/doc/internals/en/algorithms.html" target="_top">MySQL
        Internals: Important Algorithms and Structures</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-strings"></a>String Type Storage Requirements</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334799440"></a><a class="indexterm" name="idm46444334797952"></a><p>
        In the following table, <em class="replaceable"><code>M</code></em> represents
        the declared column length in characters for nonbinary string
        types and bytes for binary string types.
        <em class="replaceable"><code>L</code></em> represents the actual length in
        bytes of a given string value.
</p>
<div class="informaltable">
<table summary="Storage required for string types."><col width="40%"><col width="60%"><thead><tr>
            <th scope="col">Data Type</th>
            <th scope="col">Storage Required</th>
          </tr></thead><tbody><tr>
            <td scope="row"><code class="literal">CHAR(<em class="replaceable"><code>M</code></em>)</code></td>
            <td>The compact family of InnoDB row formats optimize storage for
              variable-length character sets. See
              <a class="xref" href="innodb-storage-engine.html#innodb-compact-row-format-characteristics" title="COMPACT Row Format Storage Characteristics">COMPACT Row Format Storage Characteristics</a>.
              Otherwise, <em class="replaceable"><code>M</code></em> ×
              <em class="replaceable"><code>w</code></em> bytes, <code class="literal">&lt;=
              <em class="replaceable"><code>M</code></em> &lt;=</code> 255, where
              <em class="replaceable"><code>w</code></em> is the number of bytes
              required for the maximum-length character in the character
              set.</td>
          </tr><tr>
            <td scope="row"><code class="literal">BINARY(<em class="replaceable"><code>M</code></em>)</code></td>
            <td><em class="replaceable"><code>M</code></em> bytes, 0 <code class="literal">&lt;=
              <em class="replaceable"><code>M</code></em> &lt;=</code> 255</td>
          </tr><tr>
            <td scope="row"><code class="literal">VARCHAR(<em class="replaceable"><code>M</code></em>)</code>,
              <code class="literal">VARBINARY(<em class="replaceable"><code>M</code></em>)</code></td>
            <td><em class="replaceable"><code>L</code></em> + 1 bytes if column values require 0
              − 255 bytes, <em class="replaceable"><code>L</code></em> + 2 bytes
              if values may require more than 255 bytes</td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYBLOB</code></a>,
              <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TINYTEXT</code></a></td>
            <td><em class="replaceable"><code>L</code></em> + 1 bytes, where
              <em class="replaceable"><code>L</code></em> &lt;
              2<sup>8</sup></td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a>, <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a></td>
            <td><em class="replaceable"><code>L</code></em> + 2 bytes, where
              <em class="replaceable"><code>L</code></em> &lt;
              2<sup>16</sup></td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMBLOB</code></a>,
              <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT</code></a></td>
            <td><em class="replaceable"><code>L</code></em> + 3 bytes, where
              <em class="replaceable"><code>L</code></em> &lt;
              2<sup>24</sup></td>
          </tr><tr>
            <td scope="row"><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGBLOB</code></a>,
              <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">LONGTEXT</code></a></td>
            <td><em class="replaceable"><code>L</code></em> + 4 bytes, where
              <em class="replaceable"><code>L</code></em> &lt;
              2<sup>32</sup></td>
          </tr><tr>
            <td scope="row"><code class="literal">ENUM('<em class="replaceable"><code>value1</code></em>','<em class="replaceable"><code>value2</code></em>',...)</code></td>
            <td>1 or 2 bytes, depending on the number of enumeration values (65,535
              values maximum)</td>
          </tr><tr>
            <td scope="row"><code class="literal">SET('<em class="replaceable"><code>value1</code></em>','<em class="replaceable"><code>value2</code></em>',...)</code></td>
            <td>1, 2, 3, 4, or 8 bytes, depending on the number of set members (64
              members maximum)</td>
</tr></tbody></table>
</div>
<p>
        Variable-length string types are stored using a length prefix
        plus data. The length prefix requires from one to four bytes
        depending on the data type, and the value of the prefix is
        <em class="replaceable"><code>L</code></em> (the byte length of the string).
        For example, storage for a
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT</code></a> value requires
        <em class="replaceable"><code>L</code></em> bytes to store the value plus three
        bytes to store the length of the value.
      </p><p>
        To calculate the number of bytes used to store a particular
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">CHAR</code></a>,
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>, or
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> column value, you must take
        into account the character set used for that column and whether
        the value contains multibyte characters. In particular, when
        using a <code class="literal">utf8</code> Unicode character set, you must
        keep in mind that not all characters use the same number of
        bytes. <code class="literal">utf8mb3</code> and <code class="literal">utf8mb4</code>
        character sets can require up to three and four bytes per
        character, respectively. For a breakdown of the storage used for
        different categories of <code class="literal">utf8mb3</code> or
        <code class="literal">utf8mb4</code> characters, see
        <a class="xref" href="charset.html#charset-unicode" title="10.9 Unicode Support">Section 10.9, “Unicode Support”</a>.
      </p><a class="indexterm" name="idm46444334731504"></a><a class="indexterm" name="idm46444334730016"></a><a class="indexterm" name="idm46444334728528"></a><p>
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>,
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a>, and the
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> and
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> types are variable-length
        types. For each, the storage requirements depend on these
        factors:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
            The actual length of the column value
          </p></li><li class="listitem"><p>
            The column's maximum possible length
          </p></li><li class="listitem"><p>
            The character set used for the column, because some
            character sets contain multibyte characters
</p></li></ul>
</div>
<p>
        For example, a <code class="literal">VARCHAR(255)</code> column can hold a
        string with a maximum length of 255 characters. Assuming that
        the column uses the <code class="literal">latin1</code> character set (one
        byte per character), the actual storage required is the length
        of the string (<em class="replaceable"><code>L</code></em>), plus one byte to
        record the length of the string. For the string
        <code class="literal">'abcd'</code>, <em class="replaceable"><code>L</code></em> is 4 and
        the storage requirement is five bytes. If the same column is
        instead declared to use the <code class="literal">ucs2</code> double-byte
        character set, the storage requirement is 10 bytes: The length
        of <code class="literal">'abcd'</code> is eight bytes and the column
        requires two bytes to store lengths because the maximum length
        is greater than 255 (up to 510 bytes).
      </p><p>
        The effective maximum number of <span class="emphasis"><em>bytes</em></span> that
        can be stored in a <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> or
        <a class="link" href="data-types.html#binary-varbinary" title="11.3.3 The BINARY and VARBINARY Types"><code class="literal">VARBINARY</code></a> column is subject to
        the maximum row size of 65,535 bytes, which is shared among all
        columns. For a <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column
        that stores multibyte characters, the effective maximum number
        of <span class="emphasis"><em>characters</em></span> is less. For example,
        <code class="literal">utf8mb4</code> characters can require up to four
        bytes per character, so a <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a>
        column that uses the <code class="literal">utf8mb4</code> character set
        can be declared to be a maximum of 16,383 characters. See
        <a class="xref" href="optimization.html#column-count-limit" title="8.4.7 Limits on Table Column Count and Row Size">Section 8.4.7, “Limits on Table Column Count and Row Size”</a>.
      </p><p>
        <code class="literal">InnoDB</code> encodes fixed-length fields greater
        than or equal to 768 bytes in length as variable-length fields,
        which can be stored off-page. For example, a
        <code class="literal">CHAR(255)</code> column can exceed 768 bytes if the
        maximum byte length of the character set is greater than 3, as
        it is with <code class="literal">utf8mb4</code>.
      </p><p>
        The <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a> storage engine supports
        variable-width columns. This means that a
        <a class="link" href="data-types.html#char" title="11.3.2 The CHAR and VARCHAR Types"><code class="literal">VARCHAR</code></a> column in an NDB Cluster
        table requires the same amount of storage as would any other
        storage engine, with the exception that such values are 4-byte
        aligned. Thus, the string <code class="literal">'abcd'</code> stored in a
        <code class="literal">VARCHAR(50)</code> column using the
        <code class="literal">latin1</code> character set requires 8 bytes (rather
        than 5 bytes for the same column value in a
        <code class="literal">MyISAM</code> table).
      </p><p>
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">TEXT</code></a> and
        <a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">BLOB</code></a> columns are implemented
        differently in <a class="link" href="mysql-cluster.html" title="Chapter 22 MySQL NDB Cluster 8.0"><code class="literal">NDB</code></a>; each row in a
        <code class="literal">TEXT</code> column is made up of two separate parts.
        One of these is of fixed size (256 bytes), and is actually
        stored in the original table. The other consists of any data in
        excess of 256 bytes, which is stored in a hidden table. The rows
        in this second table are always 2000 bytes long. This means that
        the size of a <code class="literal">TEXT</code> column is 256 if
        <em class="replaceable"><code>size</code></em> &lt;= 256 (where
        <em class="replaceable"><code>size</code></em> represents the size of the row);
        otherwise, the size is 256 +
        <em class="replaceable"><code>size</code></em> + (2000 ×
        (<em class="replaceable"><code>size</code></em> − 256) % 2000).
      </p><a class="indexterm" name="idm46444334687824"></a><p>
        The size of an <a class="link" href="data-types.html#enum" title="11.3.5 The ENUM Type"><code class="literal">ENUM</code></a> object is
        determined by the number of different enumeration values. One
        byte is used for enumerations with up to 255 possible values.
        Two bytes are used for enumerations having between 256 and
        65,535 possible values. See <a class="xref" href="data-types.html#enum" title="11.3.5 The ENUM Type">Section 11.3.5, “The ENUM Type”</a>.
      </p><a class="indexterm" name="idm46444334683760"></a><p>
        The size of a <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> object is
        determined by the number of different set members. If the set
        size is <em class="replaceable"><code>N</code></em>, the object occupies
        <code class="literal">(<em class="replaceable"><code>N</code></em>+7)/8</code> bytes,
        rounded up to 1, 2, 3, 4, or 8 bytes. A
        <a class="link" href="data-types.html#set" title="11.3.6 The SET Type"><code class="literal">SET</code></a> can have a maximum of 64
        members. See <a class="xref" href="data-types.html#set" title="11.3.6 The SET Type">Section 11.3.6, “The SET Type”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-gis"></a>Spatial Type Storage Requirements</h3>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334676000"></a><a class="indexterm" name="idm46444334674512"></a><a class="indexterm" name="idm46444334673024"></a><p>
        MySQL stores geometry values using 4 bytes to indicate the SRID
        followed by the WKB representation of the value. The
        <a class="link" href="functions.html#function_length"><code class="literal">LENGTH()</code></a> function returns the
        space in bytes required for value storage.
      </p><p>
        For descriptions of WKB and internal storage formats for spatial
        values, see <a class="xref" href="data-types.html#gis-data-formats" title="11.4.3 Supported Spatial Data Formats">Section 11.4.3, “Supported Spatial Data Formats”</a>.
</p>
</div>
<div class="simplesect">
<div class="titlepage">
<div>
<div class="simple">
<h3 class="title"><a name="data-types-storage-reqs-json"></a>JSON Storage Requirements</h3>

</div>

</div>

</div>
<p>
        In general, the storage requirement for a
        <a class="link" href="data-types.html#json" title="11.5 The JSON Data Type"><code class="literal">JSON</code></a> column is approximately the
        same as for a <code class="literal">LONGBLOB</code> or
        <code class="literal">LONGTEXT</code> column; that is, the space consumed
        by a JSON document is roughly the same as it would be for the
        document's string representation stored in a column of one
        of these types. However, there is an overhead imposed by the
        binary encoding, including metadata and dictionaries needed for
        lookup, of the individual values stored in the JSON document.
        For example, a string stored in a JSON document requires 4 to 10
        bytes additional storage, depending on the length of the string
        and the size of the object or array in which it is stored.
      </p><p>
        In addition, MySQL imposes a limit on the size of any JSON
        document stored in a <code class="literal">JSON</code> column such that it
        cannot be any larger than the value of
        <a class="link" href="server-administration.html#sysvar_max_allowed_packet"><code class="literal">max_allowed_packet</code></a>.
</p>
</div>

</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="choosing-types"></a>11.8 Choosing the Right Type for a Column</h2>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334659360"></a><a class="indexterm" name="idm46444334657904"></a><p>
      For optimum storage, you should try to use the most precise type
      in all cases. For example, if an integer column is used for values
      in the range from <code class="literal">1</code> to
      <code class="literal">99999</code>, <code class="literal">MEDIUMINT UNSIGNED</code> is
      the best type. Of the types that represent all the required
      values, this type uses the least amount of storage.
    </p><p>
      All basic calculations (<code class="literal">+</code>,
      <code class="literal">-</code>, <code class="literal">*</code>, and
      <code class="literal">/</code>) with <a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a>
      columns are done with precision of 65 decimal (base 10) digits.
      See <a class="xref" href="data-types.html#numeric-type-syntax" title="11.1.1 Numeric Data Type Syntax">Section 11.1.1, “Numeric Data Type Syntax”</a>.
    </p><p>
      If accuracy is not too important or if speed is the highest
      priority, the <a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a> type may be
      good enough. For high precision, you can always convert to a
      fixed-point type stored in a
      <a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a>. This enables you to do all
      calculations with 64-bit integers and then convert results back to
      floating-point values as necessary.
</p>
</div>
<div class="section">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a name="other-vendor-data-types"></a>11.9 Using Data Types from Other Database Engines</h2>

</div>

</div>

</div>
<a class="indexterm" name="idm46444334643920"></a><a class="indexterm" name="idm46444334642464"></a><a class="indexterm" name="idm46444334640976"></a><a class="indexterm" name="idm46444334639488"></a><a class="indexterm" name="idm46444334638000"></a><p>
      To facilitate the use of code written for SQL implementations from
      other vendors, MySQL maps data types as shown in the following
      table. These mappings make it easier to import table definitions
      from other database systems into MySQL.
</p>
<div class="informaltable">
<table summary="Mapping of MySQL data types to data types from other vendors."><col width="35%"><col width="55%"><thead><tr>
          <th scope="col">Other Vendor Type</th>
          <th scope="col">MySQL Type</th>
        </tr></thead><tbody><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BOOL</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BOOLEAN</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a></td>
        </tr><tr>
          <td scope="row"><code class="literal">CHARACTER VARYING(<em class="replaceable"><code>M</code></em>)</code></td>
          <td><code class="literal">VARCHAR(<em class="replaceable"><code>M</code></em>)</code></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">FIXED</code></a></td>
          <td><a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT4</code></a></td>
          <td><a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">FLOAT8</code></a></td>
          <td><a class="link" href="data-types.html#floating-point-types" title="11.1.4 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE"><code class="literal">DOUBLE</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT1</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">TINYINT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT2</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">SMALLINT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT3</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MEDIUMINT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT4</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">INT</code></a></td>
        </tr><tr>
          <td scope="row"><code class="literal">INT8</code></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">BIGINT</code></a></td>
        </tr><tr>
          <td scope="row"><code class="literal">LONG VARBINARY</code></td>
          <td><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMBLOB</code></a></td>
        </tr><tr>
          <td scope="row"><code class="literal">LONG VARCHAR</code></td>
          <td><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT</code></a></td>
        </tr><tr>
          <td scope="row"><code class="literal">LONG</code></td>
          <td><a class="link" href="data-types.html#blob" title="11.3.4 The BLOB and TEXT Types"><code class="literal">MEDIUMTEXT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MIDDLEINT</code></a></td>
          <td><a class="link" href="data-types.html#integer-types" title="11.1.2 Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT"><code class="literal">MEDIUMINT</code></a></td>
        </tr><tr>
          <td scope="row"><a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">NUMERIC</code></a></td>
          <td><a class="link" href="data-types.html#fixed-point-types" title="11.1.3 Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC"><code class="literal">DECIMAL</code></a></td>
</tr></tbody></table>
</div>
<p>
      Data type mapping occurs at table creation time, after which the
      original type specifications are discarded. If you create a table
      with types used by other vendors and then issue a
      <code class="literal">DESCRIBE <em class="replaceable"><code>tbl_name</code></em></code>
      statement, MySQL reports the table structure using the equivalent
      MySQL types. For example:
    </p><pre data-lang="sql" class="programlisting">mysql&gt; <strong class="userinput"><code>CREATE TABLE t (a BOOL, b FLOAT8, c LONG VARCHAR, d NUMERIC);</code></strong>
Query OK, 0 rows affected (0.00 sec)

mysql&gt; <strong class="userinput"><code>DESCRIBE t;</code></strong>
+-------+---------------+------+-----+---------+-------+
| Field | Type          | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| a     | tinyint(1)    | YES  |     | NULL    |       |
| b     | double        | YES  |     | NULL    |       |
| c     | mediumtext    | YES  |     | NULL    |       |
| d     | decimal(10,0) | YES  |     | NULL    |       |
+-------+---------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
</pre>
</div>

</div>
<div class="copyright-footer">

</div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="charset.html">Prev</a></td>
<td width="20%" align="center"><a accesskey="u" href="">Up</a></td>
<td width="40%" align="right"> <a accesskey="n" href="functions.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Chapter 10 Character Sets, Collations, Unicode</td>
<td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
<td width="40%" align="right" valign="top">Chapter 12 Functions and Operators</td>
</tr>
</table>
</div>
</body>
</html>
